Sandbox for Proposed Challenges

This "sandbox" is a place where Code Golf users can get feedback on prospective challenges they wish to post to main. This is useful because writing a clear and fully specified challenge on your first try can be difficult, and there is a much better chance of your challenge being well received if you post it in the sandbox first.

Sandbox FAQ

Posting

Write your challenge just as you would when actually posting it, though you can optionally add a title at the top. You may also add some notes about specific things you would like to clarify before posting it. Other users will help you improve your challenge by rating and discussing it.

When you think your challenge is ready for the public, go ahead and post it, and replace the post here with a link to the challenge and delete the sandbox post.

Discussion

The purpose of the sandbox is to give and receive feedback on posts. If you want to, feel free to give feedback to any posts you see here. Important things to comment about can include:

• Parts of the challenge you found unclear
• Problems that could make the challenge uninteresting or unfit for the site

You don't need any qualifications to review sandbox posts. The target audience of most of these challenges is code golfers like you, so anything you find unclear will probably be unclear to others.

If you think one of your posts needs more feedback, but it's been ignored, you can ask for feedback in The Nineteenth Byte. It's not only allowed, but highly recommended!

It is recommended to leave your posts in the sandbox for at least several days, and until it receives upvotes and any feedback has been addressed.

Other

Search the sandbox / Browse your pending proposals

The sandbox works best if you sort posts by active.

To add an inline tag to a proposal use shortcut link syntax with a prefix: [tag:king-of-the-hill]. To search for posts with a certain tag, include the name in quotes: "king-of-the-hill".

Get the Sandbox Viewer to view the sandbox more easily!

Hanabi playing bot

Overview

Hanabi is a cooperative card game with limited communication. It won the German "Spiel des Jahres" award in 2013.

The game can be played by 2-5 players, each of which has a hand of 5 cards (4 cards for 4-5 players), which they can't see themselves, but the other players can. In each turn, you can either play or discard a card, or give one other player a hint about their cards.

Common goal is to play out the cards in each color in ascending order.

As this is a cooperative game, each answer needs to cooperate with other instances of itself.

I/O format

Option 1: stateless, for all languages

Your program is called once for each turn (and is supposed to terminate afterwards). It will receive the current game state via standard input, and reply with an action via standard output. Invalid output means this game is counted as forfeited (lost, 0 points).

Input

Input is a line-based ASCII-format, with a prefix indicating what kind of data it is. The last line of the input is the current turn number (see below). Input will be in this order:

1. Meta-information: n:  n = number of players (2 .. 5) y:  you = own player id (1 .. n)

2. visible cards of the other players:

• c 1: cards for player 1
• ...
• c n: cards for player n

The cards for you are omitted in the list (you don't see your own cards).

Each card has a color (one of r, y, g, b, w) and a number (1 to 5), written like r1 or y5, comma-separated.

Example: c 2: w4,y1,g2,r3 means that player 2 has a white 4, a yellow 1, a green 2 and a red 3, in this order, on her hand.

3. Hints given about each player's cards, in a similar list:

• h 1: hints for player 1
• ...
• h n: hints for player n

For each card (in the same order as before), all hints are noted, in a comma-separated list. We also note negative information, i.e. when a card was present when a hint was given, but was not selected, by prefixing with !. For example 5 is a card which is known as 5 but of unknown color, w1 is a card which is known as a white 1, 3!y is a 3 which is known as not yellow, g!15 is a green card which is known as neither being a 1 nor 5.

For example, h 2: ,y!2,2!yr,r means that for player 2, the first card is completely unknown (was taken after the last hint), the second card is known as yellow and as not a 2, the third card is known as a 2 which is neither red nor yellow, and the fourth card is known as red.

4. p color: number – already (successfully) played out cards (one per line). Here we just note the highest card of each color.

• p r: 2 means for red, the 1 and two were played out (i.e. red 3 is the next one to play).
• p w: 0 means no white card was played out yet (i.e. the white 1 is the next one to play).
5. d:  – Discarded cards A list of all cards which were either intentionally discarded or unsuccessfully played out, comma-separated.

For example, d: w3,b5,y2,y2 means that white 3, blue 5 and two yellow 2s were already discarded.

6. game status information (each on one line, in this order): lh:  number of hints left, ld:  number of discards left (those two always sum to 8), lb:  number of "bad plays" left lc:  number of cards left in the deck t:  current turn number

(The input will be closed here.)

Output

The action to take. One of

• h  player-id   color or number – give a hint to another player. E.g. h 4 y will give player 4 a hint which of his cards are yellow. h 3 1 will give player 3 a hint which of her cards are a 1. This action is only possible if the number of hints left is positive. (The number of hints left will be reduced by 1, the number of discards will be increased by 1.)
• p  card# – play one of your own cards (identified by its number (1..5)). (If this card fits into the cards already played, it's added there. (If this is the last 5, the game ends immediately with full score (25)). Otherwise it is discarded and the number of bad plays is reduced by 1. If it reaches 0, the game ends (unsuccessfully).)
• d  card# – discard one of your own cards (idenfified by its number (1..5)). This is only possible if the number of discards is positive. (The number of hints left will be increased by 1, the number of discards will reduced by 1).

After playing or discarding a card, this card is removed from the hand, and a new card is drawn from the deck and is added to the list of cards of this player (on the left). (The hints are automatically updated.)

Option 2 (stateful)

Your program receives a live transcript of everything what happens (including the actions of the other players, and the results thereof). The controller will read one line of output from the program when it's its turn.

Input

Most input lines have the same format as before.

Initial input (as for the stateless version):

1. Meta information (n: , y: )
2. other player's cards (as before)
3. hints for cards (as before)
4. played cards (initially just p r: 0, p w: 0, etc.)
5. discarded cards (initially just d: )
6. game status, ending with t: 1.

After each player's turn:

1. a line is given with that player's action: a player id:  the action as defined in the output, e.g. a 1: h 4 y means that player 1 gave a hint to player 4 about yellow cards
2. Those parts of the card situation which changed, e.g. c and d lines if a player discarded a card (or unsuccessfully played a card) and drew a new one), c and p lines if a player played out a card successfully, a h line if a player gave a hint.
3. Updated status information, e.g. lh + ld when hint was given or a card discarded, lc when a new card was drawn, lb when a card was played unsuccessfully.
4. t:  indicating the next turn number.

*(TODO: Do we need an indication that's now your turn? That can be calculated by y == t mod n, but an explicit prompt might be easier to handle.

When the game ends, the input will be closed. (Your bot should terminate then.)

Output

As in the stateless version, one line indicating the player's action.

Option 3/4 (JVM only, stateless or statefull)

To be defined. As I will be writing the controller in a JVM language, it should be possible/easy to provide a Java API to be implemented by the bots.

Other game rules:

I tried to give most of the details above, but here are some which might be missing/unclear:

• There are three × 1, two × 2 to 4 and one 5 in each of the five colors (50 cards in total, 10 per color).

• When playing with 2 or 3 players, each player has 5 cards, when playing with 4 or 5 players, each player has 4 cards in their hand.

• If you have three bad plays (i.e. the lb counter reaches 0), you lose immediately. This is counted as score 0.

• If you succeed to play all 25 cards (i.e. all 5s are played successfully), you win immediately, with a score of 25.

• When the drawing deck is exhausted, one more round is played (i.e. each player has one more turn), then the game ends and the final score is the number of cards successfully played out.

Competition Rules

• While for human play, the amount of extra communication is "subject to negotiation", here I want to explore what is possible with just what the rules provide. Any communication between your bot instances (except as provided by the defined interface, i.e. via game actions) is strictly forbidden. Strategy needs to be encoded in the source code, not discussed during the game.

• There is also no communication between your individual games (i.e. no persistence).

• I will nominate an overall winner, and one for the stateless category. (The stateful ones have a bit more information, so they could emulate the stateless ones.)

• I will run contestants 1000 times with random decks of cards, once for each number of players from 2 to 5. If your bot only works with a specific number of players, state this in your answer. The competition score is the average score for all the runs. [I'll need to experiment to see how this varies, maybe I'll increase or decrease the count.]

• A bot needs to provide output in a reasonable time (to be defined). The stateless version needs to terminate after providing output, the stateful one keeps running, but should terminate after end of input (i.e. after the game ended).

• I will provide the controller on Github, feel free to test your bot with it (and compare it with other competition entries).

• The programming language needs to have an interpreter or compiler which is available free of cost for Ubuntu 20.4 (otherwise I can't run your bot to score it).

• I reserve the right to not run a bot when I suspect malicious code in it.

• This still needs to be refined, and I actually need to write (and test) the controller. I won't post it before that is done. Jan 17 '21 at 23:22
• What tags should this get? code-competition? Jan 17 '21 at 23:23

Write a Length interpreter

Length is a simple stack-based esolang where instructions are encoded as line lengths The instruction set is as follows:

Line Length Name Description
9 inp Pushes the ascii value of the first byte of stdin to the stack.
10 add Adds the top two values on the stack and pushes the result onto the stack.
11 sub Subtracts the top two values on the stack and pushes the result onto the stack.
12 dup Duplicates the top value of the stack.
13 cond If the top value of the stack is 0, skip the next instruction. Then pop it.
14 gotou Sets the program counter to the value of the line under the instruction.
15 outn Pops the top of the stack, and outputs it as a number.
16 outa Pops the top of the stack, and outputs its ascii value.
20 mul Multiplies the top two values on the stack and pushes the result onto the stack.
21 div Divides the top two values on the stack and pushes the result onto the stack.
24 gotos Sets the program counter to the value at the top of the stack

In case the table doesn't work, here is the esolangs page: https://esolangs.org/wiki/Length
Test inputs are too long to put here, they can be found here
helloworld.len - Outputs Hello, World!
truth.len - A truth machine
bottles.len - Outputs the lyrics to 99 bottles of beer
This is a code golf, so shortest program wins!

• table is broken, it looks fine in preview Jan 18 '21 at 20:49
• Fixed. But this should be reported on SE Meta.
Jan 18 '21 at 20:56

Your task is to create a program which takes the other program's source as input and output the index of the byte that should be deleted from the other program. (zero-indexed)

Each program will be radiated at the same time. The first program to fail to return a valid index after being radiated loses (whether by compiler error, runtime exception, out-of-bounds output, or some other means), or it is considered a draw if both fail at the same time.

Each program will compete against each other program. The program receives 1 point per round survived. The overall winner is the one with the most points.

Programs are limited to a length of 1024 bytes.

Alternate possibilities:

(Inspired by @Dingus) A hash of the opponent's original source code and a list of the indexes of bytes deleted so far is passed in instead of the current source code, making it a bit more of a blind guess as to what you radiate. If at any time, a program makes a guess it has already made, it loses. This turns it into a sort of "Radiation Battleship"

• Interesting challenge. How will it be tested, if different languages are allowed?
– user
Jan 19 '21 at 19:12
• @user it shouldn't be terribly difficult to make a shell-based controller. Submissions would probably need to include compiler flags or shebangs separately so that the controller knows exactly how to run the program. Jan 19 '21 at 19:19
• That would work for "practical" languages, but I'm a bit worried about esolangs. I guess TIO can probably deal with that, though.
– user
Jan 19 '21 at 19:20
• If Program A has all its bytes deleted before Program B does, does B win? I'm imagining a pathological scenario in which A is empty and outputs by exit code. Jan 19 '21 at 23:46
• Also, wouldn't something like this be impossible to beat? Jan 20 '21 at 0:12
• @Dingus I suppose that would be impossible to beat. I wonder how I could make things different with resisting arbitrary insertions... probably not viable though. Jan 20 '21 at 16:14
• To prevent fixed-output programs, could you perhaps tie the indexing to the unmodified code? In other words, force the output to be different every round? Jan 20 '21 at 22:22
• @Dingus I think that might work (implying that both the original program and guesses are passed to the program), but there's probably another similar edge case I'm missing. Kinda turns it into radiation battleship. If a program returns a guess it has already made, it instantly loses. Jan 20 '21 at 23:58
• Following that thought, it might be kind of interesting if some opaque id (e.g. a hash of the source code) is passed in instead of the current state of the source code. Jan 21 '21 at 0:02
• @Beefster what's the point of the hash? (what can submissions do with it?) Jan 21 '21 at 4:37
• @thedefault. the hash is only used to assign a distinct id to each program and it could be used to seed a random number generator. Jan 21 '21 at 16:16
• @Beefster I thought submissions aren't supposed to be designed to beat specific opponents (and the only way to use a hash is to optimize to beat specific opponents) (and providing a hash of an unknown string as input just in case somebody wants to seed a RNG with it is a weird decision) Jan 22 '21 at 16:47
• Also, if the length of the source code is not known, it's effectively impossible to make guesses that are guaranteed not to be out-of-bounds. (also, I expect 90% answers to this challenge to output something like 0,1,2,3,4,5,...) Jan 22 '21 at 16:58

Print a 3D shape

Posted

• Suggestion: use characters other than • and ¶ as they are multi-byte characters which not all languages will handle easily. ASCII characters instead would be better Jan 20 '21 at 21:12
• I modified them, thank you. Jan 20 '21 at 21:35
• @caridCoinheringaahing I was just looking to try some other character taking as reference this ASCII table. The two characters that I changed are numbers 166 and 167 of the table. I am confused. Jan 21 '21 at 23:45
• Most languages can handle code points between 32 and 127 inclusive. Some use custom code pages (e.g. Jelly) that won't necessarily have extended ASCII characters, but will have regular ASCII Jan 21 '21 at 23:48
• Oh all right thank you for the clarification! Jan 21 '21 at 23:55
• @Davide the table you linked is not actually an ASCII table. ASCII only goes from 0 to 127; there are more code pages that extend it to 256 and the creator of that table has clearly picked one. This confusion arises because almost all code pages include ASCII as the first 128 and then extend with some symbols like ¶ on top of that. Nowadays most things use UTF-8 which encodes some characters with more than one byte and can use millions of different characters from Unicode Jan 22 '21 at 7:58
• @pxeger Oh thank you for this definitive explanation! Jan 22 '21 at 13:02

Quine Countdown! quinecode-golf

Write a program that accepts a single parameter n and outputs another program that outputs another program etc until the nth call outputs the original input n again.

Scoring is a modified version of codegolf: For input 100, add together the code length of each program in the chain, excluding the final 100. This is your score. Lowest score wins!

• Actually it's not much harder than a typical quine program. Because 100 is so large, most programs will do it the general quine way. Jan 29 '21 at 7:18
• Besides, the score would be easier to read if the score is the average size instead of the maximum. Jan 29 '21 at 7:18
• "Because 100 is so large, most programs will do it the general quine way." That's the intention. It's a quine with something extra. Without the scoring rule, everyone would just build nested multi-escaped prints, which isn't as interesting. Feb 9 '21 at 11:07

Counting set bits in a byte

Here is a bite-sized problem I ran in to when trying to implement Conway's game of life on a microcontroller, and was trying to count the amount of neighbours: How can you check how many bits are set in a byte?

Challenge

Given one byte of input data and an integer N between 0 and 8, check if there are exactly N bits set in the byte.

Test cases

N = 0, input = 0b00000001 -> False
N = 0, input = 0b00000000 -> True
N = 3, input = 0b01001001 -> True
N = 3, input = 0b11100000 -> True
N = 3, input = 0b00001111 -> False
N = 7, input = 0b11101111 -> True
N = 7, input = 0b11111110 -> True
N = 8, input = 0b11111111 -> False


Sandbox question

• My first intuition to solving this problem was to shift the bits out one by one, AND with 0x01 and count them. I feel however it must be possible to do something more efficient in terms of CPU cycles used. How can I make a challenge that is about optimizing instruction count and memory usage rather than on program-size? I have seen the tag, but I don't know what scoring method best to use.

Edit: Closing after some good comments and possible solutions

Arnauld and CristoLosoph gave some great comments and led me to conclude that my issue is maybe to hardware/language specific to fit in a nice coding challenge. CristoLosoph showed me this interesting code snippet which I think is quite efficient:

uint8_t count_bits(uint8_t x){
x = ((x & 0b10101010) >> 1) + (x & 0b01010101);
x = ((x & 0b11001100) >> 2) + (x & 0b00110011);
x = ((x & 0b11110000) >> 4) + (x & 0b00001111);
return x;
}


Two other things I learned:

• Some hardware have a builtin POPCNT instruction in their instruction set, and gcc has a __builtin_popcount() method that does exactly what I was looking for
• I found in this question that it's an interesting trade-off (as with most embedded functions probably) to just make a lookup table containing all 256 possible return values. It takes some memory but not too much.

I also learned that probably would have been a good fit for this type of challenge!

Once again thanks for the interesting comments!

• Hello RvdV. Hm, seems like your motivation does not really fit. Fastest-code and smallest code is not the same, rather opposite things. When you program microcontrollers you are very restricted in the language but code golfing is the opposite (if you do not specifically restrict languages to one single one). Of course, there is a very performant solution for bitcount in the language which you might be looking for which however is quite uninteresting for code golf. I'll post you a fast snippet in C below. Jan 29 '21 at 10:20
• Jan 29 '21 at 10:25
• You may consider using atomic-code-golf, but be aware that it's pretty hard to specify correctly. Jan 29 '21 at 10:26
• x = ((x & 0xAAAAAAAA) >> 1) + (x & 0x55555555); x = ((x & 0xCCCCCCCC) >> 2) + (x & 0x33333333); x = ((x & 0xF0F0F0F0) >> 4) + (x & 0x0F0F0F0F); x = ((x & 0xFF00FF00) >> 8) + (x & 0x00FF00FF); x = ((x & 0xFFFF0000) >> 16) + (x & 0x0000FFFF); You only need the first 3 lines if you only need it for 8-bit integers and then you can cut the hexadecimal literals down to two digits. Jan 29 '21 at 10:29
• But if you work with GCC, please use __builtin_popcount() since that is the function that the compiler people tried to optimize exactly for your purpose and for your selected architecture. Jan 29 '21 at 10:31
• Thanks a lot for your comments Arnauld and ChrisoLosoph! You are right that it's hard to define, and I didn't realize even how much language but also hardware-bound my problem was, maybe it's too difficult to define indeed (and if you define it language-agnostic it becomes the related post Arnauld linked). I will update the post with you suggestions!
– RvdV
Jan 29 '21 at 17:51

Mix my colors

This challenge is inspired by the Color Alchemy Patch on NetHack, notably incorporated by UnNetHack 3.5.2.

Objective

Given two strings indicating colors, mix them according to the rules below, then output it.

Colors

There are 16 colors in total that are valid inputs. They are categorized to 8 chromaticities and 2 brightnesses, like below:

        Light    Dark
Hueless white    black
Red     pink     ruby
Blue    sky-blue indigo
Yellow  yellow   golden
Orange  orange   amber
Green   emerald  dark-green
Purple  puce     magenta
Brown   ochre    brown


(I'm omitting gray, for it will make this challenge just cumbersome in this regard.)

Note that all color names are in lowercase.

Color-mixing rules

• Above all, mixing colors is idempotent.

• Mixing colors is commutative unless noted below.

• When mixing two primary colors (Red, Blue, or Yellow):

• If they have same chromaticities, the result will also be in the same chromaticity.

• Mixing Red and Blue results in Purple.

• Mixing Red and Yellow results in Orange.

• Mixing Blue and Yellow results in Green.

• When mixing two secondary colors (Orange, Green, or Purple):

• If they have same chromaticities, the result will also be in the same chromaticity.

• All other combinations result in Brown.

• For all cases covered by above, mixing two Light (resp. Dark) colors will result in corresponding Light (resp. Dark) color.

• For all cases covered by above, mixing a Light color and a Dark color shall result in either Light or Dark. This is the only rule that may break the commutativity.

• Mixing a Light color with black results in corresponding Dark.

• Mixing a Dark color with white results in corresponding Light.

• All combinations not covered by above fall in don't care situation.

Examples

Valid outputs

• Mixing white and white results in white.

• Mixing pink and pink results in pink.

• Mixing pink and ruby results in either pink or ruby.

• Mixing ruby and golden results in amber.

• Mixing sky-blue and ruby results in either puce or magenta.

• Mixing emerald and dark-green results in either emerald or dark-green.

• Mixing emerald and orange results in ochre.

• Mixing puce and amber results in either ochre or brown.

• Mixing white and ruby results in pink.

• Mixing ochre and black results in brown.

Don't care situations

• Mixing pink and white falls in don't care situation. There is no rule that covers this case.

• Mixing ochre and brown falls in don't care situation. There is no analogous rule for tertiary colors.

• Mixing indigo and magenta falls in don't care situation. There is no rule for mixing a primary color and a secondary color.

• Mixing indigo and orange falls in don't care situation.

• Mixing pink and ochre falls in don't care situation.

• Mixing white and black falls in don't care situation. (In the game, it results in gray, but I'll ignore this, for sake of simplicity of this challenge.)

Rules for code golf

• Input format is flexible. In particular, it can be two strings, or one string separating colors by whitespaces. It's implementation-defined whether to accept leading or trailing whitespaces.

• Output format is also flexible. Outputting leading or trailing whitespaces is okay.

• Invalid inputs fall in don't care situation.

• The rule looks clear enough, but you can provide a table of 256 possible outputs just to be extra sure. Jan 31 '21 at 1:57

Longest Common Suffix

Given arbitrarily many (more than 4) words, your goal is to find the longest common suffix of all of them.

Rules

1. The suffix shouldn't be longer than one third of the length of any word, and should be longer than 2 characters.
2. The words can have at most one "exception" among them, that is, it doesn't have the same suffix others have. You should ignore these "exceptions".
3. If no suffix can satisfy all rules above, do not make any output.
4. All given words are separated by spaces; they only contain lower case English alphabets.
5. You can use any way to accept input, but output should only be in STDOUT.

Example

Given: television operation delegation repetition
Output: ion

Given: vision decision subtraction observation
Output:


Why? The suffix, ion, is longer than 1/3 the length of vision and decision. There're two exceptions.

Given: interested congratulated excited overjoyed
Output: ted


Why? overjoyed is an exception, because others have the suffix ted, but it doens't. So we ignore the word overjoyed.

Given: abcdefghijkl bcdefghijkl cdefghijkl defghijkl
Output: jkl


Why? defghijkl is the longest, but it is longer than 1/3 the length of defghijkl.

This is code golf, so the shortest code win.

It's not recommended to use built-in functions which directly returns the result.

• Most answerers prefer "any (standard) way to get output" as well, but it's up to you. Practically, it's mostly not a problem. Feb 1 '21 at 9:30
• Regarding the output "No common...", people don't like hard coding long error messages, it would be better received if it's changed to "any value that signifies that there isn't...". Feb 1 '21 at 9:31

Compile Roman Numerals to <some language>

Your code will, given an integer i, output code code(i) in any programming language that will evaluate to (print, push, return) i by itself. code(i) ++ code(i') should evaluate to i + i' for an i' <= i and i' - i for an i' > i. You do not have to handle cases like code(1) ++ code(2) ++ code(3) where there are more than one number less than 3 before 3, but you should handle code(5) ++ code(3) ++ code(4) => 6 with more than two numbers.

Clarification: the generating code takes a number, not a roman numeral, but the generated code is expected to have the behaviour of a roman numeral when concatenated with other outputs.

Examples

if  yourcode(10) -> 'X'
and yourcode(5)  -> 'V'
then eval('XV')  -> 15.

if  yourcode(1)  -> 'I'
and yourcode(10) -> 'X'
and yourcode(5)  -> 'V'
then eval('XIV') -> 14

if  yourcode(7)  -> 'a'
and yourcode(3)  -> 'b'
then eval('ab')  -> 10
and  eval('ba')  -> 4


Scoring

Your answer is scored by the total bytes of the generating code.

• Sandbox: how do I explain this? what tags does this get as a challenge that requires an answer that generates code? Feb 1 '21 at 14:48
• Any upper limit?
Feb 1 '21 at 15:21
• @Adám no, besides any restrictions on integers built-in to the language. Feb 1 '21 at 15:25
• This sounds very difficult. The code snippets would need to carry a state.
Feb 1 '21 at 15:36
• Can the code take something like 7 (not representable as a single character in Roman numeral) as input? Feb 1 '21 at 15:43
• @user202729 yes, they would need to handle other numbers Feb 1 '21 at 15:44
• What should something like eval(code(7) + code(5)) evaluate to? Feb 1 '21 at 15:46
• @user202729 13 because 7 > 5. Feb 1 '21 at 15:47
• How do you define "Roman numeral" then? (when digits can take values other than the standard values) Feb 1 '21 at 15:48
• @user202729 OK, I've now defined how any integers should be handled when next to eachother. Feb 1 '21 at 16:07
• So, given a sequence $p_1,\ldots p_n$ where there's no $p_i < p_{i+1} < p_{i+2}$, the result of $\operatorname{exec}(\operatorname{generate}(p_1) + \ldots + \operatorname{generate}(p_n))$ (where $+$ denotes concatenation) should be $p_n + \sum _{i=1} ^{n-1} p_i \times (-1)^{[p_i < p_{i+1}]}$, right? Feb 1 '21 at 16:30
• @user202729 I guess so, although I'm not good at reading math :P. Feb 1 '21 at 16:35

Posted

• Clearly defined enough (not very interesting) -- except that is it guaranteed that the value exists? Feb 1 '21 at 3:14
• @user202729 Oh thank you, I forgot to cover this. I think that in case it doesn't exist, we can output a something like the smallest integer in the array. I would like to not restrict the input at all. Feb 1 '21 at 12:03
• Possible test case: empty array. (by the way don't patch "edit" into the sandbox post, include it in the text itself) Feb 2 '21 at 2:58
• @user202729 thank you, I edited the challenge. I will add test cases, including the empty array. Feb 2 '21 at 10:26

Golf this Thumb-2 constant!

• Not very related to the question, but have you tried using some size-optimization option of some existing compiler? (-Os) Feb 1 '21 at 9:32
• Otherwise, clear enough. Feb 1 '21 at 9:33
• I explained the pattern better, and the last pattern does cover the rest, but it isn't the shortest. Feb 4 '21 at 0:43
• Okay. (just to check, there are $4862 > 2^{12} = 4096$ distinct values represented with the Imm12 format, right?) Feb 4 '21 at 0:53
• Yes. There are 4096 possible encodings for the Imm12 format. Feb 4 '21 at 1:48
• Then I must understand something wrong, because (as I've said above) there are 4862 different values that can be encoded.) Feb 4 '21 at 1:51
• Oh yeah I was wrong. I think I am going to go back to it just being a byte rotated, even if it isn't accurate. As the true encoding is too complex to be fun to calculate. 🤷‍♂️ Feb 4 '21 at 3:02

(this is the core of the BF memory optimizer challenge.)

(At the moment I still need to make some test cases; however you can still review the rest of the challenge.)

note: This problem is reducible from Simple Max Cut, therefore it's NP-complete. (https://doi.org/10.1016/0304-3975(76)90059-1)

note: While I did get a bunch of test cases from this site, I'm not sure how can I write a reasonable algorithm to compete with...

Proof

(actually this is not part of the sandbox challenge, but I'll post it here because it's related)

First, for convenience, assume that the problem is represented by a undirected graph, where the number of rows/columns of the matrix is equal to the number of nodes, and the corresponding weight is the sum of the value of the edges connecting the corresponding two nodes.

With that representation, the value to be minimized is the sum of the product of the edge lengths and the edge weights, with the graph nodes embedded into the point $$\ 1, 2,\ldots, |V| \$$.

From a Simple Max Cut problem of the form:

Given $$\ n \$$ variables $$\ x_1, x_2,\ldots, x_n \$$, maximize the value of $$\ \sum_{i=1}^m [a_i \ne b_i] \$$, where each of $$\ a_i, b_i \$$ represents either a variable or its negation.

It can be transformed to an instance of this problem:

First, construct $$\ 2n \$$ nodes on a graph, denoted $$\ p_1, p_2,\ldots, p_n, q_1, q_2,\ldots, q_n \$$. Let $$\ a \$$ be some positive integer. Connect those vertices:

• $$\ p_1 \$$ and $$\ q_1 \$$, with cost $$\ 2n^2 a \$$,
• the 4 pairs of vertices $$\(p_1, p_i),(p_1, q_i),(q_1, p_i),(q_1, q_i)\$$ with cost $$\ (n+1-i) a \$$, for each $$\ i=2, 3,\ldots, n \$$,
• and some other edges with small weights (the sum of their weights should be less than $$\a\$$ -- (1)) that mainly does not affect the optimal configuration.

The sum of the edge weights (except the first one) is $$\ 4 ((n-1)+(n-2)+\ldots+1)a=2n(n-1)a \$$.

The edge between $$\ p_1 \$$ and $$\ q_1 \$$ has a weight larger than the sum of all the others, it's obvious to see that in the optimal (minimum cost) configuration, these two must be adjacent.

Then, regardless where those 2 vertices are placed, the $$\ i \$$'th smallest distance-pair to those are at least the $$\ i \$$'th value in the sequence are

$$(1, 2),(1, 2),(2, 3),(2, 3),(3, 4),(3, 4),\ldots,(n-1, n),(n-1, n)$$

.

And by the rearrangement inequality, it's optimal to place the weight so that the vertices with the smaller edge-weight to $$\ p_1, q_1 \$$ are placed further from the vertices. Therefore the only optimal placement is

$$z_n, z_{n-1}, \ldots, z_2, z_1, z_1, z_2, \ldots, z_{n-1}, z_n$$

where each $$\ z_i \$$ is either $$\ p_i \$$ or $$\ q_i \$$ ($$\1 \le i \le n\$$).

Encode the condition "vertex $$\ i \$$ is on the left side of the cut" by "$$\ p_i \$$ is to the left of $$\ q_i \$$ in the permutation". (2)

Assuming that the edge weights are allowed to be fractional.

For each condition (in the Simple Max Cut problem) that "there's an edge between vertices $$\u\$$ and $$\v\$$ ($$\ u\le v \$$)", add an edge between $$\ p_u \$$ and $$\ q_v \$$ with weight $$\\frac 1 {2u-1}\$$ to this problem.

The weight of this edge can either be $$\ u-v \$$ or $$\ u-v+(2u-1)\$$ in the configuration that minimizes the total weight of the edges constructed in the previous section.

Therefore, if the vertices $$\ u \$$ and $$\ v \$$ are on different sides of the cut (according to the encoding (2)), the total weight is decreased by $$\ 1 \$$ if $$\ u \$$ and $$\ v \$$ are on different sides; and the configuration with the minimum weight is exactly the one with maximum number of edges cut.

However, in the actual problem edge weights must be an integer. We replace each edge weight $$\\frac 1 {2u-1} \$$ by $$\\lceil\frac c {2u-1}\rceil \$$, where $$\ c=2nm\$$.

Because there are $$\ m \$$ edges in total, if the sum of any $$\ k-1 \$$ increment values $$\\lceil\frac c {2u-1}\rceil (2u-1) \$$ is strictly less than the sum of any $$\ k \$$ increment values, for $$\1\le k\le m \$$, then the optimal sum is also the maximum cut.

Observe that because $$\ c=2nm \$$ and $$\ x\le 2n-1 \$$, each increment value must be between $$\ 2nm \$$ (inclusive) and $$\ 2nm+2n-1 \$$ (exclusive). Therefore the maximum sum of $$\ k-1 \$$ values is $$\ (2nm+2n-2)(k-1) \$$, which is less than the minimum sum of $$\ k \$$ values $$\ 2nmk \$$ when $$\ 1\le k\le m \$$.

The sum of all those does not exceed $$\ \lceil \frac {2nm}{1} \rceil m \$$. Therefore if $$\ a \$$ is chosen to be $$\ 2nm^2+1 \$$, then the condition (1) is satisfied.

Minimum cost matrix permutation

(or ? Obviously the latter would be more useful in practice code golf)

Given a matrix $$\w\$$ in $$\{\mathbb N_0}^{n\times n}\$$, define the symmetric matrix $$\d\$$ in $$\{\mathbb N_0}^{n\times n}\$$ by the formula $$\d_{i,j}=\left| i-j \right|\$$, find a permutation matrix $$\P\$$ such that the sum of elements in the matrix $$\(P^{\mathsf T} \cdot w \cdot P ) \,\odot\,d\$$ (where $$\\odot\$$ denotes the Hadamard product/element-wise product) is smallest.

The result will be the mean (TODO: median? mean of the 50% maximum? mean result/naive ratio?) of the score over these test cases, for as long as you can run your program.

(WIP) Settling the Lands of Codegolfia

The challenge controller will randomly generate a 200x200 map representing the terrain of the land

Your task is to write an AI whose goal is to have the largest population after 500 turns.

Start

Each player begins with 1 cell claimed and a population of 100.

Turns

On each turn, you have the opportunity to claim land cells. You can claim 1 cell per turn, plus 1 per 1000 population. Claimed cells must be orthogonally adjacent to a cell you already own. You cannot claim cells belonging to other players.

Turns happen simultaneously. In the event that two players attempt to claim the same cell, both players will lose 10 people from their population and neither player will claim the cell.

At the end of your turn, your population grows by 10% (rounded up), up to the maximum size your colony can support.

Population Support

Without any land claimed, your colony can support up to 150 people.

Supporting larger populations requires claiming land. Each terrain type increases the amount by some amount. Combinations of terrain expand this further.

Terrain

There are 4 terrain types:

• Plains
• Supports 20 people by itself
• Supports 5 per adjacent owned plains
• Forest
• Supports 10 people by itself
• Supports 5 per adjacent owned forest
• Supports 50 additional people if there are at least 10 owned plains cells within 10 cells (Manhattan distance)
• Mountains
• Supports 5 by itself
• Supports 5 per owned plains within 15 cells
• Supports 10 per owned forest within 5 cells
• Water
• Each plains cell can support 500 additional people if it is within 5 cells of an owned water cell.
• Each forest cell can support 200 additional people if it is within 10 cells of an owned water cell.

Alternative ideas for terrain

• Plains support raw population. Same as above
• Forest cells increase population support for all plains within 5 cells by a factor of 5% (stacks multiplicatively)
• For every water cell and 10 plains cells, reproduction rate increases by 1%
• Each mountain cell increases the range of each owned mountain and forest within 3 cells by 1. (stacks additively)
• I was just thinking of something like this! (but different enough I can still do mine :p). Currently I don't see too many options for strategy other than comparing each orthagonal square each turn and picking the best. Feb 11 '21 at 19:38
• @RedwolfPrograms yeah. Maybe I should make each of the terrains more mechanically different. Maybe one increases reproduction rate, one expands synergy range, and another enhances the others. Feb 11 '21 at 20:24
• That sounds like a good idea, depending on how it's implemented. Maybe being close to water would let you claim extra land per turn near the body of water, sort of like exploration? Feb 11 '21 at 20:31

Score an approximation code challenge code-golf

Given a list of inputs (strings) and their expected outputs (integers or floats)[1], and a black-box program[2], calculate the score using the following scoring system:

Let $$\R_n\$$ be the expected output of the $$\n^{th}\$$ input, let $$\A_n\$$ be the actual output given by the black-box program, and let $$\ j \$$ be the total number of input/output pairs. (All values are positive and non-zero)

Then the score is defined as: $$S=\left\lceil L\times\max_{1\le i \le j}\left({\max\left(\frac{A_i}{R_i},\frac{R_i}{A_i}\right)^2}\right)\right\rceil$$ where $$\L\$$ is the length of the black-box program in bytes.

Example:

If the size of the program is $$\100\$$ bytes and the worst approximation is on the input "moon", where the program outputs $$\1000\$$ instead of the expected $$\1737\$$, then the score would be:

$$S=\left\lceil 100\times{\left(\frac{1737}{1000}\right)^2}\right\rceil=302$$

This system is taken shamelessly from this challenge by @Arnauld. Here is his reference implementation.

[1]: You may take the inputs and outputs either zipped ([(in1, out1), (in2, out2), ...]), or not zipped (([in1, in2, ...], [out1, out2, ...]), with both lists of the same length), at your option.

[2]: You may take the black-box program as either:

• a black-box function, and its length in bytes, as two separate inputs
• a string of code to be evaluated, as one input (the length will not be given separately unless necessary)

Rules

• (1) is it a problem if the program only support integers? (2) is it guaranteed that both values (actual and submission output) are strictly positive? The formula is not well defined when either value is zero. Feb 15 '21 at 13:17
• @user202729 all values will be positive; the idea was that you can support integers or floats, whichever is easier Feb 15 '21 at 13:23
• The "whichever is easier" part is currently not mentioned in the challenge. Feb 17 '21 at 10:36

Stack half full or half empty? (worldview of a programming language)

Is the glass half full or half empty? It's a common rethoric question to determine a person worldview, which can be optimistic or pessimistic based on the answer given. If i were dealing with a machine i would probably ask "Is the stack half full or half empty?" Let's try and see if programming languages have a worldview too.

Write a full program or a function which prints or returns one of "The stack is half full." or "The stack is half empty." when given as input the question "Is the stack half full or half empty?" but wait.. you have to provide a stack to be observed.. which stack you provide is up to you: input one or check an already existing stack. Your solution will then output one of the two sentences mentioned above for a non empty / non full stack, your choice which one to print, just make sure your answer is as short as possible because this is . For an empty stack it must produce the "empty" output while for a full stack "full".

Survey

I will make a chart of the pessimistic Vs optimistic languages based on the half outputs. If you find the same byte count for both choices you can provide both, in which case they will count on both sides of the chart, but you just can select one if you like.

input

• A sentence in any reasonable method.
• The behavior is defined only for the question "Is the stack half full or half empty?" and exactly this.
• Indeed your solution can also completely ignore the input as long as it works with the specified input.
• Question mark is mandatory.

output

• One of "The stack is half full." or "The stack is half empty.", for a non full / non empty stack.
• "full" or "empty" for a full stack or an empty stack respectively
• upper / lower case or a mix are fine.
• ending dot not mandatory.

Rules

• Only the mentioned input allowed.
• Loopholes allowed.
• This is and the answer with the fewer bytes of source code wins.
• This would be a really cool challenge, but the tasks are too similar. I doubt anything other than print "The glass is half full" will be competitive. Maybe add an additional thing they have to do, in addition to printing the text? As an example, for half empty, take a number of inputs and discard every second one. For half full, print every other fibonacci number. Feb 18 '21 at 20:41
• So undefined behaviour is fine for all inputs that are not one of the two specific questions?
Feb 18 '21 at 20:41
• Your initial description only mentions one possible input, while your "input" section mentions both.
Feb 18 '21 at 20:42
• Thanks @Redwolf Programs ! To be honest I had this crazy idea but don't really knew how to make it interesting.. I ended developing it in the simplest and most obvious way.. Maybe I 'll change many things during the sandbox Feb 18 '21 at 20:48
• @Adám yes for UB, for the input I'm sorry, my fault.. Initially I was using only one question but then decided it was reasonable to handle both combinations.. Gonna edit thanks! Feb 18 '21 at 20:51
• @Redwolf Programs I changed a bit, I hope this stack thing will add some flavor without exiting the context, please let me know if you want to share some opinions Feb 21 '21 at 18:43
• @Adám some changes.. If you have any opinions please let me know Feb 21 '21 at 18:45
• @AZTECCO I still think half empty and half full should require doing different things. Currently I doubt anyone will pick half empty, because half full is shorter and there's no other difference. Feb 22 '21 at 0:24
• @Redwolf Programs yeah that's true. I was wondering if languages with built in string compression, string methods or regex would compete the plain print"..answer.." method which should be around 25~30 of score but.. I don't know.. I just feel like a do this or that based on input is a different challenge but it seems to be the only way Feb 22 '21 at 9:21
• @AZTECCO The concept of the answers choosing between two options is really cool and unique; the current options are just too similar. Maybe one thing that tests control flow, like a truth machine sort of thing, and one that tests input/output, like discarding every other output? The stack validating thing (where you have to print empty or full) feels kind of irrelevant to the cool part of the challenge. Having the input be the question isn't really necessary IMO; you could replace the input with something like a list of numbers (cont.) Feb 22 '21 at 16:19
• (cont.) and have the answers do one of two things with that list (totally up to you, although I'd recommend tasks that use different capabilities of the language, like one control flow and one math), then print The glass is half (empty|full). Feb 22 '21 at 16:20
• @Redwolf Programs thanks for explaining your opinion, your insight are really important and I totally agree, I was losing the scope and your words got me back on track! Feb 22 '21 at 19:27

Bytewise look-and-say sequence code-golf

The look-and-say sequence is a sequence which begins with 1, 11, 21, 1211, 111221, 312211. To get a term of the sequence from the previous, read the previous out literally:

312211 => one three, one one, two twos,two ones => 13112221

So the next term is 13112221.

Given this javascript code (Node.js), which outputs the look-and-say sequence indefinitely, delimited by newlines:

function nextTerm(x){
return x.replace(/(.)\1*/g,z=>z.length+z[0])
}
function printUpTo(x){
var str = '1';
for(var i = 0; i < x; i++){
console.log(str);str = nextTerm(str);
}
}
printUpTo(Infinity)


It will output a string that begins 1\n11\n21\n1211\n111221 etcetera. Your job is to write a function that takes a number as input and outputs that byte of the output string.

Rules

You may output a different character for newline instead of \n, e.g. # or something.

Scoring

Your program should be able to handle 100 million.

The first answer to handle 1e+18 correctly will receive a 100-rep bounty. This cannot be hard-coded.

Standard loopholes apply.

Test cases:

1 => \n
5 => 2
10 => 1
20 => 3
50 => 3
100 => 1
1000 => 1
100000 => 3
10000000 => 1


This is , so shortest bytes wins.

• Note that restricted-complexity means "solutions' time complexity must be polynomial in the input size" or something similar. "In a minute" means restricted-time, but then you have to specify the specification of your machine and test all solutions (although in most cases it will be obvious and you don't need to) Feb 20 '21 at 9:39
• And an implementation of the naive algorithm in a low-overhead language (C++) would be able to do that as well. Feb 20 '21 at 9:40
• @user202729 I'm not actually sure how to write this myself - notice that there isn't a testcase for 1 billion - that's because I couldn't figure out how to do an actually efficient version. Also, by 'In a minute', I mean on TIO. I'll add that. Feb 20 '21 at 9:44
• And TIO isn't suitable for timing submissions (personally I think it's really suitable, but people don't agree.) Feb 20 '21 at 9:45
• @user202729 What do you mean? Is it something to do with how busy the server is or similar? Feb 20 '21 at 9:46
• codegolf.meta.stackexchange.com/questions/12707/… Feb 20 '21 at 9:48
• @user202729 Ok, redoing the whole thing, since I don't want to install loads of different compilers/interpreters. Feb 20 '21 at 9:50
• Ok, publishing. Feb 22 '21 at 4:30
• Wait, I did warn you that a naive implementation in C++ would be able to do it. Feb 22 '21 at 4:30
• Do you want to allow that? Feb 22 '21 at 4:31
• Ok, 1e+12 should be fine. Feb 22 '21 at 4:31
• Wait are you sure that there actually is a polynomial time solution? Feb 22 '21 at 4:32
• I feel like there should be one, but I don't know. Never mind. Feb 22 '21 at 4:33
• Actually there probably isn't since there's no way to calculate the nth term or length of nth term without calculating the previous. So never mind. Feb 22 '21 at 4:36
• There probably is. (I didn't come up with one.)Although people could let their programs run for a month. 1e+18 is definitely safe, but might be a little too large for some polynomial approaches. Feb 22 '21 at 4:36

Self improving program

In this challenge you will write a program or function which when run will output a faster solution to this challenge.

Formally speaking: you will write a program or function, $$\T_0\$$, which takes an integer $$\x\$$ as input and outputs a program or function (in the same language), $$\T_1\$$, which is itself a valid solution to this challenge, such that there exists a function $$\f\$$ where $$\T_1\$$ is in the time complexity class $$\O\left(f\right)\$$, but $$\T_0\$$ is not. That is to say the output program must have a strictly faster asymptotic time complexity.

Note that since $$\T_1\$$ must be a valid solution to the challenge it must output a program or function $$\T_2\$$ which is even faster, and so on and so forth, creating an infinite chain each faster than the last.

Answers will be scored by their length in bytes with fewer being better.

Precision

In keeping with the tradition of this site, and to remain inclusive: The order notation of a function will be assumed to be measured by the algorithm implemented by your answer. Thus we will pretend not to notice the behavior of your actual program for inputs out of the range of your language's numeric type.

However that being said, in order to ensure that you are actually changing the algorithm at every step, for constants initialized in your program this leniency is not given. e.g. If you use a double precision floating point 1.0000000000000001 is equal to 1.0. So if your method relies on an increasing or decreasing constant embedded in the program you should be careful that the algorithm actually changes.

Simply put for $$\T_n(x)\$$ you are forgiven for errors arising from very large $$\x\$$, but not from very large $$\n\$$.

• (which is the same thing is $T_0\in o(T_1)$.) Feb 20 '21 at 9:54
• How is this possible? You'd need to get faster and faster, and even if you do it exponentially, you can't change the speed by tiny fractions of a second each time. Please explain, very confused. Feb 20 '21 at 9:54
• And what prevents programs from doing for i in range(int(n**1.00001)): pass? Feb 20 '21 at 9:55
• Thinking about it again, since programs can simply run a loop to have any asymptotic complexity (>= complexity to parse input), it's not that hard. And you could just ask programs to print out an always-decreasing floating point value plus the new program. Feb 20 '21 at 9:57
• @user202729 But the always-decreasing float is the problem here, because eventually it will get too small to be distinguished by the language from 0. Feb 20 '21 at 10:01
• @Ausername An easier way to have it constantly decreasing is to have O(n^2) -> O(n log(n)) -> O(n log(log(n))) -> O(n log(log(log(n)))) etc. This approaches O(n) from above and remains distinguishable for really large inputs, without requiring anything finicky about precision.
– Wheat Wizard Mod
Feb 20 '21 at 10:02
– Wheat Wizard Mod
Feb 20 '21 at 10:17
• It means that programs doing things like (Python) n=1000000000000000000000000000000; for i in range(int(input())**(1+1/n): pass and (1+1/n) evaluates to 1 (because of IEEE754, even though the value of n is stored exactly) will fail? Feb 20 '21 at 11:45
• @user202729 Yes. Precision rules are always pretty non-concrete and non-objective. I think it is best to not try to push at the boundaries.
– Wheat Wizard Mod
Feb 20 '21 at 12:49

Posted at Convert Gemtext to HTML but moved here to discuss

Gemtext is a very simple markup format used by the alternative web protocol Gemini. Write a Gemtext to HTML converter.

From the Wiki:

A line of text is a paragraph, to be wrapped by the client. It is is independent from the lines coming before or after it.

A list item starts with an asterisk and a space. Again, the rest of the line is the line item, to be wrapped by the client.

A heading starts with one, two, or three number signs and a space. The rest of the line is the heading.

A link is never an inline link like it is for HTML: it’s simply a line starting with an equal-sign and a greater-than sign: “⇒”, a space, an URI, and some text. It could be formatted like a list item, or like a paragraph. Relative URIs are explicitly allowed.

Example:

# This is a heading
This is the first paragraph.
* a list item
* another list item
This is the second paragraph.
=> http://example.org/ Absolute URI
=> //example.org/ No scheme URI
=> /robots.txt Just a path URI


This should produce this HTML tree (just the equivalent tree, not the exact formatting):

<h1>This is a heading</h1>
<p>This is the first paragraph.</p>
<ul>
<li>a list item</li>
<li>another list item</li>
</ul>
<p>This is the second paragraph.</p>
<a href="http://example.org/">Absolute URI</a>
<a href="//example.org/">No scheme URI</a>
<a href="/robots.txt">Just a path URI</a>


HTML in the text must be escaped, e.g paragraph <p> is cool becomes <p>paragraph &ltp&gt is cool</p>.

This is so the shortest code in bytes wins

• Can you clarify "whitespace ... doesn't matter"? Mar 1 '21 at 19:30
• @Wezl edited question Mar 1 '21 at 19:36
• What parts of HTML do we need to handle? Can we convert every character (even unreserved ones like A) to its entity number? Is the input guaranteed to be ASCII only or do we need to handle other characters? I don't know Gemtext well enough to ask about it, but are there escape characters or something that would allow mapping, say, to HTML: <p># A paragraph</p>? Mar 1 '21 at 19:53

Dedekind, cut!

Objective

Given a Dedekind cut and a nonnegative integer $$\n\$$, print the real number represented by the Dedekind cut up to $$\n\$$ precisions, rounded.

Dedekind cut

A Dedekind cut representing a real number $$\x\$$ is a boolean-valued function on $$\\mathbb{Q}\$$ that gives a falsy value for rational numbers under $$\x\$$, and a truthy value otherwise.

Note that Dedekind cuts can represent arbitrary real numbers. Irrational, nonconstructible, transcendental, or even uncomputable numbers.

Rules

• Direction of rounding is implementation-defined.

• For the inputted Dedekind cut, it shall accept arbitrary rational numbers. That is, the numerator and the denominator must be arbitrary-length integers. (Though the denominator is nonzero, of course) Accepting the rational number as a pair of integers is acceptable. In this case, the denominator is expected to be positive, and the fraction is expected to be irreducible.

• Invalid inputs fall in don't care situation. This also applies to the rational numbers the Dedekind cut accepts.

• Note that negative numbers also must be handled. For nonnegative numbers, however, it is implementation-defined whether to output a leading plus sign.

• Outputting leading or trailing whitespaces is permitted.

• All digits after the decimal point shall be considered significant in this regard. The amount of significant digits after the decimal point must be exactly $$\n\$$. Trailing zeros cannot be discarded.

• If $$\n = 0\$$, the decimal point may be omitted.

• If the decimal representation has no significant digits before the decimal point, the leading zero may be omitted.

• The omission from the previous two rules cannot be present simultaneously.

Examples

• For $$\x = 0\$$ and $$\n = 0\$$, output one of 0, 0., +0, and +0..

• For $$\x = 0\$$ and $$\n = 2\$$, output one of .00, 0.00, +.00, and +0.00.

• For $$\x = ½\$$ and $$\n = 0\$$, output one of 0, +0, 1, +1, 0., +0., 1., and +1..

• For $$\x = ½\$$ and $$\n = 3\$$, output one of .050, 0.050, +.050, or +0.050.

• For $$\x = \sqrt{2}\$$ and $$\n = 3\$$, output either 1.414 or +1.414.

• For $$\x = -\pi\$$ and $$\n = 3\$$, output -3.142. Note the rounding.

Ungolfed solution

An implementation with exponential time complexity.

import Text.Printf

showDedekind :: (Rational -> Bool) -> Int -> String
showDedekind x n = go (0.5 * 10 ^^ negate n)
where
go p = let
epsilon = 10 ^^ negate n
in if x p
then if x (p - epsilon)
then go (p - 2 * epsilon)
else let
str = printf "%0*d" n (floor (p / epsilon) :: Integer)
(str1, str2) = splitAt (length str - n) str
in str1 ++ '.' : str2
else go (p + epsilon)

• So to be precise, the input value x is actually given as a black-box function, right? For output format, I recommend to keep it simple. You can even omit it entirely so that we can assume a convenient format for each language in use (under default I/O rules). Should the solutions theoretically support arbitrarily large x (with both signs)? Mar 2 '21 at 9:08

Let's rise higher!

(I am posting this challenge in sandbox because this kind of exceptional challenges are often closed, and then downvoted to oblivion, so I want to get your feedback and with kind help you fix the specifications in this challenge, and make it interesting, Thanks!)

Challenge

The main objective of the challenge is pretty simple, this is an answer chaining contest, where you have to serially print numbers from 1. That means User 1's answer will print 1, then User 2's answer will print 2 and so on. But there are some rules to make the contest tougher.

Rules

• You can't use the characters of the source code used in the previous answer.

• Each answer cannot use more than 12 distinct bytes.

• You cannot post 2 answers in a row, let me explain, suppose you have written answer no. 5, now you cannot write answer no. 6, you have to wait someone to post a valid answer no. 6 (That prints 6 without using characters in answer no. 5), and after that you can write a valid answer no. 7 following the rules.

• Program cannot take input or access internet.

• Standard loopholes apply.

Scoring criterion

This is not challenge, so there is a custom objective scoring criteria. Try to make your score higher.

• Each answer's initial score is 1. (Only chain beginning answer has score 0).

• For each distinct byte you use, your score is increased by the number of distinct bytes. That means if your number of distinct bytes is 6, then your score increases by 1+2+3+4+5+6, and if your number of distinct bytes is 7, then your score increases by 1+2+3+4+5+6+7 and so on.

• You have to calculate distinct byte difference with the previous answer, and add/subtract score using the 2nd rule. So if byte difference is 3 then you will get a +1+2+3 score, or if -3 (Previous answer has 3 more distinct bytes than yours), then -1-2-3.

• For first 40 bytes you will get a 0.15 score, but from then you have to minus 0.5 score. An example if your score has total 45 bytes then your score bonus will be (40*0.15)-(5*0.5)=6-2.5=3.5, so you have to add +3.5 to your score. (The score criteria is to encourage medium length smart answers.)

A total example:

Suppose,

• Your previous answer has 4 distinct bytes, and a total of 20 bytes
• Your answer has 7 distinct bytes, and a total of 56 bytes

Distinct byte difference: (7-4)=3
Total score: 1+(1+2+3+4+5+6+7)+(1+2+3)+(40*0.15)-(16*0.5)=33


So you get a score of 33 for this condition.

# Answer Number. Language Name, x Bytes, y Distinct bytes, Score: Z

source code

(TIO/Any other interpreter link) -> Not required, but preferred


example

1. Powershell, x Bytes, y Distinct Bytes, Score: Z

......


Winning criterion

Winner will be determined after 30 days, winner is determined by total score. But users are welcome to continue the chain after that!

Suppose you have three answers with score 33,16,78 then your total score will be 33+16+78=127.

And there is two special prizes from me after 30 days:

• +150 bounty for the winner.
• +50 bounty for the single answer with highest score! (Such as man of the match in Cricket)

1. PowerShell, 1 byte, 1 distinct byte, Score: 0

1


Try it online!

---

Meta

• Are all rules clear?

• Please improve the scoring criterion and rules. (Especially please improve the second rule, I am not very sure about that.)

• Please make me a javascript snippet for leaderboard, to sort users by their total score.

• There are a bunch of small things that could be clarified (particularly the scoring), but I think there is a larger problem you should try to fix first. Answer-chaining challenges rely on the task becoming more difficult as more answers are posted, but since you are only restricted by the previous response getting an optimal score will probably not be difficult until the number of answers is very large (much larger than 100). If you fix this, then the problem becomes that if finding a good answer is difficult, posting for more score becomes a race, which usually isn't fun. Mar 3 '21 at 18:32
• @FryAmTheEggman if the number of answers are large, then you would sort the question by active. What are the other problems please say. Mar 4 '21 at 6:58
• The number of answers being large isn't the problem. Please re-read my comment - it is talking about how the challenge isn't a good answer-chaining challenge because the approach for each link in the chain is too similar. Try writing what you think the next solution would be, and the one after that, and I think you will start to see the problem. Mar 4 '21 at 14:42

Finish what John McCarthy started (WIP) code-golfinterpreterlisp

This does not have anything to do with Joseph McCarthy or communism. Some background from Wikipedia (you can skip ahead if you like):

John McCarthy published the first paper on Lisp in 1960 while a research fellow at the Massachusetts Institute of Technology. In it he described a language of symbolic expressions (S-expressions) that could represent complex structures as lists. Then he defined a set of primitive operations on the S-expressions, and a language of meta-expressions (M-expressions) that could be used to define more complex operations. Finally, he showed how the meta-language itself could be represented with S-expressions, resulting in a system that was potentially self-hosting.[3] The draft version of this paper is known as "AI Memo 8".[4]

Example M-expressions

McCarthy had planned to develop an automatic Lisp compiler (LISP 2) using M-expressions as the language syntax and S-expressions to describe the compiler's internal processes. Stephen B. Russell read the paper and suggested to him that S-expressions were a more convenient syntax. Although McCarthy disapproved of the idea, Russell and colleague Daniel J. Edwards hand-coded an interpreter program that could execute S-expressions.2 This program was adopted by McCarthy's research group, establishing S-expressions as the dominant form of Lisp.

Interpret a subset of M-expressions, where 9 primitive functions have already been defined.

Syntax

Atoms: An atom is a series of any characters excluding [, ], ;. While an atom name can include whitespace, leading and trailing whitespace is ignored. Some examples include foo, lambda (also a function name), and nil (also a list). Atoms act as both variables and data (they're like strings).

Booleans: The atom t is truthy, whereas the atom nil is falsy.

quote: A series of expressions between square brackets, delimited by semicolons. [a; [b; c]; de] is equivalent to the S-expression (QUOTE (A (B C) DE)). It is somewhat like this JS list: ["a", ["b", "c"], "de"].

cond: A series of if-then pairs between square brackets, delimited by semicolons, with an arrow -> (you can use any other character(s)) separating the if-then pairs. e.g. [atom[x] -> x; t -> car[x]] yields x if it's an atom, or the first element of x if it's a list. It is guaranteed that at least one of the cases will be true.

Function application: Functions can be called using functionname[arg1; arg2; ...; argN].

• car - Return the first element of its argument.
• cdr - Return its argument without the first element.
• cons - Prepend its first argument to its second argument.
• eq - Check if its two arguments are equal.
• atom - Check if its argument is an atom.
• lambda - Define an anonymous function using the syntax lambda[[param1; param2; ...; paramN]; bodythatusesparams].
• label - Store a function using a name. For example, label[drop2; lambda[[xs]; cdr[cdr[xs]]]] defines a function drop2 that drops the first two elements of its first argument.

Rules

• Functions may use lexical or dynamic scope, or some crazy mixture of both.

Much of this question is copied from this challenge and the Wikipedia article on M-expressions.

Questions for Meta

• For cond, should I use the [condition -> res; condition2 -> res2; ...] syntax, or should I keep it like the linked challenge?
• Should answers support higher-order functions?
• Does anyone have any good examples using Mexprs?
• I did a double-take at the title, which sounds like the challenge is to root out communists still hiding in the US state department to finish what Joseph McCarthy started...
– xnor
Jan 20 '21 at 10:23
• @xnor Uh...that certainly was not what I intended. I could probably say "Finish what John McCarthy started" or just "Interpret M-expressions", although the latter sounds more boring. There's also a Eugene McCarthy, apparently, so I guess just McCarthy is too ambiguous.
– user
Jan 20 '21 at 13:59
• Mar 10 '21 at 16:41
• If you want do disallow trivial answers that use quit or comments or something, you could require all 3 programs to be irreducible. However, I think it might not be as interesting like that, because it would then just be the same as all the existing irreducible restricted-source challenges. It's still an interesting challenge to optimise the length of three similar programs with the same charset. Extra feedback: I'd recommend changing Hello, World! to another string because many languages have Hello World built-ins. Mar 10 '21 at 16:47
• Also, maybe specify that functions are allowed as well as programs, according to our I/O defaults. And can you clarify whether the Hello World has to include the quotes? Mar 10 '21 at 16:51
• @pxeger Thanks, I have updated my post and I agree that the irreducible rule is not needed. Even a "trivial" answer seems challenging to arrive at. About the string, maybe I can change it to "Hello, Permutations!" which also goes with the challenge title, but I am unsure if I should. Mar 10 '21 at 17:18
• Hello, Permutations! sounds fine - I think it would be a good idea. Again, can you clarify whether you want the double quotes around "Hello, Permutations!" to be outputted literally or not? Mar 10 '21 at 17:25
• @pxeger Changed it, and its clarified now. Mar 10 '21 at 17:29

Uppercase JSON member names

Given a single valid JSON value, uppercase all member names. That is, you must also return valid JSON that encodes an equivalent value, except that all names of members in all objects, have been converted to uppercase according to one of the Unicode methods (simple or full).

Details:

• The given value can be null, a number, a string, an array, or an object. There may therefore not be any names to convert, but such names can also "hide" as elements/members of arrays/objects in arrays/objects, …

• Dictionaries are considered unordered.

• Names and strings will only encode ASCII.

• Keys will be unique, even after case conversion.

• Floating point imprecision is tolerated.

Example input A

["a\":",{"b":"c"}]


Example outputs

["a\":",{"B":"c"}]

[
"a\":",
{
"B" : "c"
}
]


Example input B

{"h\u0065re":
"are'=",    "be"
:{"dra\u0000gons":true,"b\\e\"ar\ns":"two"},"\t":[1e-0,null,3e+2
,  {"":""} ,{
},
"name\":\"value",[false,[],[[]]]]}


Example outputs

{
"BE": {
"B\\E\"AR\nS": "two",
"DRA\u0000GONS": true
},
"HERE": "are'=",
"\t": [1,
null,
300,
{
"": ""
},
{
},
"name\":\"value",
[false,
[],
[[]]]]
}

{"BE":{"B\\E\"AR\nS":"two","DRA\u0000GONS":true},"HERE":"are'=","\t":[1,null,300,{"":""},{},"name\":\"value",[false,[],[[]]]]}

• Is order of keys in a dictionary matters? For example, input {"b":0,"a":0}, may I output {"A":0,"B":0}? Will there be any duplicate object keys? For example, is {"a":1,"a":2} a valid input? ECMA-404 allow duplicate keys, but RFC 8259 disallow it. For above input, may I output {"A":2} only? What about duplicate keys after conversion? For example, is input {"a":1,"A":2}valid? And what should I output?
– tsh
Mar 15 '21 at 6:28
• @tsh How is this?
Mar 15 '21 at 6:33
• May I assume keys only contains characters in range U+0020~U+00FE? For example, are keys like {"großes":1,"æða":2,"ｈｅｌｌｏ":3,"βῆτα":4} invalid?
– tsh
Mar 15 '21 at 6:33
• @tsh non-ASCII keys are literally mentioned in the bullet points and included in the example case.
Mar 15 '21 at 6:33
• May I output DRA\u0000GᎤNSS for dra\u0000gꭴnßinstead of DRA\u0000GᎤNß?
– tsh
Mar 15 '21 at 6:37
• @tsh Silly me for not thinking of the various methods. Addressed.
Mar 15 '21 at 6:42
• @tsh All answered: 1: "Dictionaries are unordered." 2: "Keys will be unique" 3: "Keys will be unique, even after case conversion."
Mar 15 '21 at 6:44
• May I use different unicode normalization from inputs? For example, Input {"e\u0301":1}, may I output {"\u00c9":1}? And for input {"\u00e9":1}, may I output {"E\u0301":1}?
– tsh
Mar 15 '21 at 6:47
• @tsh Good point. Addressed now. Do you think it would be an improvement to restrict input to ASCII only?
Mar 15 '21 at 6:52
• Try to support uppercase for non-ASCII would simply require submission in some languages with such a built-in support. And as code-golf context, no one would likely to handle it manually. So restrict it to ASCII only would be helpful to let more languages involved.
– tsh
Mar 15 '21 at 7:14
• @tsh Done. How is this?
Mar 15 '21 at 7:16
• You are still using "ꭴ" in it. Also suggest testcases with object in array: {"extra":[0, {"key":[[[{"inner":{}}]]]}]}
– tsh
Mar 15 '21 at 7:24
• @tsh Did you refresh? I don't see any "ꭴ". There are objects in the "\t" array.
Mar 15 '21 at 7:27
• Will input always be a json object (dictionary)? For example, another testcase ["a",{"b":"c"}], null, And maybe it need more testcases. And if I try to parse the JSON string first, may floating point errors allowed? For example, input {"a":[17706675576718736274, 300223795848957673199326286566205161047]}, may I output {"A":[17706675576718735000,3.0022379584895768e+38]}
– tsh
Mar 15 '21 at 7:31
• @tsh Good questions. Should all be addressed now.
Mar 15 '21 at 7:36

Minimally Making Change

• What is expected output for 10? To my understanding, it should be 0010, but you give 5100. Am I misunderstand something?
– tsh
Mar 16 '21 at 11:33
• @tsh They have to be able to make all cents 1-10 with the coins. So they need 5 pennies for making 1-4 and the nickel to make 9. Hopefully clarified a bit Mar 16 '21 at 12:35

Find the Best Set of Adapters

Moved here: Find the Best Set of Adapters

• This reminds me of one of the 2020 AoC challenges, don't remember exactly what the task was but it had a similar premise. (Also there's no need to disallow standard loopholes explicitly, they're disallowed by default :p) Mar 12 '21 at 1:44
• It was "Day 10: Adapter Array" but that was about finding the number of ways to reach the result and the adapters were a bit different. Mar 12 '21 at 3:42
• This looks like it'll be a fun challenge, although I'd be careful to look around because there might be a duplicate with an entirely different name/background that involves doing the exact same thing. Mar 12 '21 at 4:14
• May it contains adapter from A -> A? Although it would be not useful. It could be included in testcases. (make sure implementation will not fall into infinity loop in such case.) Will it possible 0 adapter is required (Same type for both computer and phone already)? If so, add another testcase for it.
– tsh
Mar 15 '21 at 9:00
• Also, is it possible that part of given graph is not connected to computer / phone types. For example, A, C; A->B; B->C; X->Y; Y->Z.
– tsh
Mar 15 '21 at 9:02
• Current testcases does not contains cycle. It would be helpful to include one: A, C; A->B; B->C; C->A for example.
– tsh
Mar 15 '21 at 9:04
• Your description says "Unfortunately, none of them can go straight from my phone to my computer". but your last testcase output 1. One of them should be incorrect.
– tsh
Mar 15 '21 at 9:04
• Thanks, @tsh for the great feedback. I have edited the question with your suggestions in mind. Mar 15 '21 at 18:37
• 2nd test case seems incorrect.
– tsh
Mar 16 '21 at 11:28
• @tsh thanks, fixed Mar 16 '21 at 15:45

Fortuitous Numbers

Four is Magic is a very interesting math game.

1. We start out with a number: 1
2. We spell it into English: “one”
3. We find the sum of the letters: 3
4. Go back to step 2, until the game ends at “4”

The reason “4” is Magic, is that “Four” has 4 letters, and no other number has this property.

Fortuitous Numbers

In this game, I’m making one change.

1. Take for example the number: 24.
2. Write it out in English: “twenty four”
3. Note that there are 2 words
4. Take the product of the word lengths
5. 24 - “twenty four” - 6 * 4 = 24

4 and 24 are Fortuitous Numbers. Are there any more?

The challenge

Your challenge is to create a piece of code that will generate all Fortuitous Numbers.

Specifically:

1. Solutions should be found by the program, not chached by you.
2. We never say, “one hundred and one”. Exclude the “and”
3. The only output should contain a comma separated list of only the solutions:
4,
24,
n,
m,

1. The code should have no limit as to how large the number can go. If you have trouble finding names, used the ones mentions in this Wikipedia article. This will take you smoothly to 103003 and beyond.
2. Hint: Look at the sequence, A058230.

Bonus!

1. Program generates the first 9 solutions relatively quickly (under 5 minutes time.)
2. Program also finds Fortuitous Numbers if type a -> b -> ... -> a instead of just a -> a

ROT47(code) code-golfciphersource-layout

ROT13 is a Caesar cipher where every letter is replaced by the 13th letter that follows it in the alphabet.

Every letter and its counterpart:

a b c d e f g h i j k l m n o p q r s t u v w x y z
n o p q r s t u v w x y z a b c d e f g h i j k l m

ROT47 is a deritave of ROT13 which includes all the ASCII printable characters except space. Rot47 substitutes every character with the 47th character that follows it in the ASCII range.

Every character and its counterpart:

! " # $% & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? @ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [ \ ] ^ _  a b c d e f g h i j k l m n o p q r s t u v w x y z { | } ~ P Q R S T U V W X Y Z [ \ ] ^ _  a b c d e f g h i j k l m n o p q r s t u v w x y z { | } ~ ! " #$ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? @ A B C D E F G H I J K L M N O

I ROT47( your code) and you ROT47( the output)

• Your code is supposed to at least output 1 character within the [33,126] ASCII range.
• When ROT47 is applied on your code, the output should also be ROT47 of the previous output
• solve in the fewest bytes possible

Below a ROT47 converter taken from decode

var input = document.getElementById("input");
var editor = CodeMirror(input, {
lineNumbers: true,
tabSize: 2,
mode: 'javascript',
theme: 'monokai'
});
editor.setSize(900, 100);
document.getElementById("button").onclick = function(){
editor.setValue(rot47(editor.getValue()));
}

//implementation below from https://www.dcode.fr/rot-47-cipher
// Javascript
function rot47(x){
var s='';
for(var i=0;i<x.length;i++){
var j=x.charCodeAt(i);
if((j>=33)&&(j<=126)){
s+=String.fromCharCode(33+((j+14)%94));
}
else {
s+=String.fromCharCode(j);
}
}
return s;
}
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.60.0/codemirror.min.js" integrity="sha512-hc0zo04EIwTzKLvp2eycDTeIUuvoGYYmFIjYx7DmfgQeZPC5N27sPG2wEQPq8d8fCTwuguLrI1ffatqxyTbHJw==" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.60.0/theme/monokai.min.css" integrity="sha512-R6PH4vSzF2Yxjdvb2p2FA06yWul+U0PDDav4b/od/oXf9Iw37zl10plvwOXelrjV2Ai7Eo3vyHeyFUjhXdBCVQ==" crossorigin="anonymous" />
<body style="background-color:#333333
">
<div id="input">
</div></br>
<button id="button" style="background-color: #17202a
;color:white">ROT47</button>
</body>

Meta questions:

• Is it an interesting challenge?
• Is the explanation clear?
• suggestion for a title.
• why does it look normal in edit mode but not in the result 😡. Mar 23 '21 at 19:43
• Fixed the formatting. SE doesn't show tables unless they have an empty line before and after them Mar 23 '21 at 19:56
• so valid answers and their input must be printable ASCII? Or should it ignore anything not printable? Mar 24 '21 at 16:45
• It looks like the reference implementation leaves non-printable characters and space alone. It would be helpful to specify that. Mar 24 '21 at 16:50
• Well, if you look on main, this is a alternate of an alternate of a rip-off of a rip-off of a rip-off of a rip-off of a rip-off of a rip-off. (see this). Which is not to say it's a bad challenge. Mar 25 '21 at 8:40

To count the sum of all Unicode characters of a given input under an interesting constraint

• Welcome to the site, and thank you for using the sandbox! Can you confirm that answering with a normal (base-10) number is OK?
Mar 25 '21 at 6:37
• Thanks for the comment, edited accordingly- Final answer can to be calculated in any base (either Hexadecimal, or base-10 or binary as per the program) no need to convert back. Mar 25 '21 at 9:55
• I know you've posted this already, but generally I recommend leaving challenges in the sandbox for a week.
Mar 25 '21 at 11:19
• Ohk. I will remember it from the next time. thanks a lot Mar 25 '21 at 11:19
• I've edited this down to a stub now that it's been posted to save space Mar 30 '21 at 21:38

Sum of two squares

Given an integer $$\n\$$, determine whether $$\n\$$ can be expressed as the sum of two square numbers, that is $$\\exists a,b\in\mathbb Z|n=a^2+b^2\$$.

   0 -> truthy
1 -> truthy
2 -> truthy
3 -> falsy
4 -> truthy
5 -> truthy
6 -> falsy
7 -> falsy
11 -> falsy
9997 -> truthy
9999 -> falsy


Relevant OEIS sequences:

This is , so shortest answer as measured in bytes wins.

• This is a subset of this problem.
– hyper-neutrino Mod
Mar 31 '21 at 5:29
• @HyperNeutrino yes, and I have that listed as a related problem. There's actually another method of solving this problem involving prime factors which doesn't work for that one, so I'm hoping that's novel enough to warrant a separate challenge. Mar 31 '21 at 18:16
• My bad, didn't notice the link. And yes, I don't think it'd be a duplicate here; I do agree that there will probably be unique approaches to this specific problem.
– hyper-neutrino Mod
Mar 31 '21 at 18:18
• A couple answers here used the prime-factorization approach, and a few used the approach of counting divisors of the form 4k+1 and 4k+3 respectively.
– xnor
Apr 2 '21 at 6:50