# 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!

# Capsa, a card game KotH!

Capsa, known by many times, including the name Big Two in English, is a popular card game in East Asia and South East Asia, especially throughout China, Hong Kong, Indonesia, Macau, Malaysia, Singapore and Taiwan. There are many variations and house rules. The rules of this particular variation are thus:

• This game will be played between exactly four bots. The cards are dealt between everyone, so that everyone has 13 cards.
• Rank is ordered with 2s before As as follows: 2, A, K, Q, J, 10, 9, 8, 7, 6, 5, 4, 3, hence, the name Big Two.
• Suits are ordered as follows: Spades, Hearts, Clubs, Diamonds
• Ordering runs rank first then suit. Thus, 7 of Hearts > 7 of Diamonds > 6 of Hearts, the lowest card is the 3 of Diamonds, and the highest, the 2 of Spades

You can play cards in sets of one, two or five cards, (singles, pairs, or five-card poker hands). Each set must always be bigger than the one before.

With singles, play may proceed in this way: 1 3H, 2 4H, 3 5D, 4 5C, 1 10S, 2 Pass, 3 JD, 4 Pass, 1 2S, 3 Pass

Pairs are ordered by the higher suit in the pair. 6C6H is of a lower rank than 6D6S. Play may proceed in this way: 3 3D3C, 4 6D6H, 1 6D6S, 2 JHJS, 3 Pass, 4 ADAC, 1 Pass, 2 Pass

Poker hands are ordered in the following way, from lowest in rank to highest in rank:

• Straight: Five cards that are consecutive in rank, e.g. 6H 7S 8D 9H 10C or JS QH KD AS 2C. Rank is determined by the highest card, with suit used as a tie-breaker.
• Flush: Five cards with the same suit, e.g. 5H 7H 10H QH AH Rank is determined first by suit, then by highest card.
• Full house: A three of a kind with a two of a kind, e.g. JD JS JH 3D 3S. Rank is determined by the triple, without regard for the pair.
• Straight flush: Five cards that are consecutive in rank and are all of the same suit, e.g. 6H 7H 8H 9H 10H. Ranked the same as straights, with suit as a tie-breaker
• Four-of-a-kind: Four cards of the same rank, with any 5th card, e.g. 9D 9C 9H 9S 4S This hand is known as the bomb. Wins any round of poker hands it is played in, unless someone else plays their own bomb.

Any five-card hand that is higher than the previous five-card hand played is eligible. For example, you can play a full house on a straight.

Rules of play:

• At the beginning of the game, the cards are dealt between everyone, so that everyone has 13 cards. The first player is the one that holds the 3 of Diamonds and they must play this card first, whether singly, with another 3 in a pair, or in a poker hand.
• A round begins with the first player playing a single card, a pair or a poker hand. Every other player either respond with the same number of cards (you must play singles on singles, never a pair or a poker hand), or that player passes for that round.
• A player may pass even when they have a playable card, but they must pass if none of their cards are high enough in rank, that is, if they have no playable cards. For example, in a round of poker hands, if you only have a flush as a five-card set, but another player has already played a full house, you must pass, as your flush is too low.
• The round ends when all but one player passes. That last player wins the round and starts the next round.
• The game ends when one player has played all of their cards.

Possible scoring systems:

• Bots are judged by the number of games they win over (TBD) games that they play. So if we have seven bots to test, we'll play them until every bot has played more than (TBD) games.
• Bots are judged by the number of cards they have left at the end of the game. (The winner will obviously have 0 cards at the end of the game).
• "The cards are dealt between everyone, so that everyone has 13 cards" belongs in the "rules of play" section, even if that means having to repeat it. Dec 30 '15 at 11:09
• @PeterTaylor Done. If you have any comments on the controller linked at the bottom of this post, I'd love to hear them. Thanks Dec 30 '15 at 11:27

# Let's Play Unikong

In honor of April Fool's day, we shall have an epic battle to see who can play Unikong best. Or, rather, whose program can play it best.

## Goal

Write a program in any language to play the game Unikong. It should seek to try and score as high as possible.

## Scoring

Whomever's program has the highest average score, over 10 games wins.

## Rules

Standard rules apply. Additionally, your program must actually play the game, not change the score variable by some other means, and you can read the variables from the game to avoid trolls and downvotes, but not modify any variables to make it easier. I will run the tests myself and will use the first 10 runs to calculate the score. Please include any specific instructions needed to run your program.

Notes: This would be my first question, so hopefully I got the format right. Are the rules clear enough? Do I need to clarify anything?

• Do not require a video, run the programs yourself and see how far they get without your input. No pressing continue. Apr 1 '16 at 17:09
• Uh, will that link exist beyond today? If not then I think you'd need to find a way to replicate it (not sure about copyright here...). Anyway, I'm not really sure what counts as cheating. I think it will be hard to ban everything that's bad, so it might be better to write a controller that only allows looking at certain variables and only allows the basic player input. Apr 1 '16 at 17:09
• @FryAmTheEggman I've changed the link to something that will remain after April Fool's. Apr 1 '16 at 22:02

## Specification

In this challenge, your task is to reverse the lengths of an array-of-arrays, while keeping its concatenation intact.

More explicitly, your input is an array of arrays of nonnegative integers, which you may assume to fit in the native int type of your language. The input may be an empty array or an array of empty arrays, or it may contain arrays of different lengths. You can take the input in any reasonable format.

Your output shall be another array of arrays, again in any reasonable format. The concatenation of the output shall be equal to the concatenation of the input, so it contains the same integers in the same order. However, the sequence of lengths in the output shall be the reverse of that of the input.

## Example

Consider the input array

A = [[4,10],[0],[],[3,3,2],[1]]


The concatenation of A is

B = [4,10,0,3,3,2,1]


and its length sequence is

C = [2,1,0,3,1]


The correct output is

[[4],[10,0,3],[],[3],[2,1]]


since it's the unique array with concatenation B and length sequence reverse(C).

## Rules and scoring

You con write a full program or a function. The lowest byte count wins, and standard loopholes are disallowed.

## Test cases

TODO: make more

[] -> []
[[]] -> [[]]
[[],[],[1]] -> [[1],[],[]]
[[1,2],[4,5,6]] -> [[1,2,4],[5,6]]
[[4,10],[0],[],[3,3,2],[1]] -> [[4],[10,0,3],[],[3],[2,1]]


I'm debating whether I should guarantee that the input is non-empty, and/or only contains non-empty arrays. In some languages (like J), empty arrays make the challenge significantly harder, but on the other hand, I don't want it to be too easy either.

• Just an FYI "reshape" operations pretty heavily trivialise this. I don't think it would be crazy to ban them, but it's probably fine with them also. Jun 7 '16 at 17:12
• I'd prefer the more general challenge of splitting an array the same way as another array of arrays with equally many elements.
– xnor
Jun 8 '16 at 0:28
• @FryAmTheEggman I'd prefer not to explicitly ban any builtins. If that leads to 3-byte Jelly answers, so be it. :P I also suspect Jelly would win anyway... Jun 8 '16 at 14:35
• @xnor That would be essentially be this challenge, but with only arrays-of-arrays. Do you think they would be different enough not to be duplicates? Jun 8 '16 at 14:39
• Even if the depth is fixed at 2, the shortest approach would most likely still be the be the same in many languages. It's a borderline dupe, and since it takes only one gold badge user to close a duplicate, it will probably end up closed. Jun 8 '16 at 17:23
• @Zgarb I'm not sure if I'd count it as a dupe, but I think reversed input vs general array wouldn't make much difference there. I expect most solutions would just work with the reversed input as if it were a general array.
– xnor
Jun 8 '16 at 20:50
• @xnor Reversed input has the added complexity that the same array must be used for content and shape. That's not a big problem for some languages, but I'd expect another approach to outgolf the pop/map approach with the added overhead of creating a second reference for the reversed array in, e.g., Python. I admit I haven't tried it yet though. Jun 9 '16 at 0:24
• I think what you call "concatenation" of the array is called "flattening". Oct 13 '16 at 18:24

# The Secret Handshake

This is based off of this sandbox comment.

This is a challenge of secrecy.

The goal of this KOTH is to write a program that is capable of identifying itself amongst a crowd of other programs. In order to do this, you must develop a secret handshake which will be recognized only by other copies of the same program.

A single game involves every program competing at once. There will be five instances of each program in the arena, and the winner will be the first program to correctly identify the four other copies. After a large number of games, the submission with the most victories will be the overall winner.

## The Gameflow:

1. Each program receives a number which tells the number of bots in the arena, which is five times the number of submissions. The bots are arranged in a circle, and they are each considered ID #0 from their own perspective, with N-1 being the maximum ID number.
2. Then the game cycle starts. At this point, each bot will be awaiting input.
1. Your bot will receive input consisting of an ID number and an optional message.
• For example, 7 hi means that bot #7 said hi to you.
• If the ID number is 0, then there will not be a message. This would occur if it is your turn but there is no message to receive.
2. Now, your bot is allowed to output a guess consisting of four ID numbers.
• If those four numbers are the IDs of your teammates, then your team will win that game.
• You will receive no confirmation of an incorrect guess.
3. Next, you must output a message to send. The message will be a destination ID number followed by up to 3* characters. Example messages: 7 4 w 12 #?Q.

*This number is subject to change. Larger messages make it harder to fake a secret handshake. I hope that a very short message forces people to use multi-step handshakes. It might also be interesting to limit it to 1-character messages.

# Sandbox Notes

Something that I haven't quite figured out is how the controller program will determine which bot gets to move each turn. I suppose it would be simplest go in order: Each bot has an "unread message queue" and receives/sends one message each turn. The bot immediately after you (ID #1) then moves next.

Alternatively, there could be a set turn order which is unrelated to the ID order, simply to make it impossible for one bot to tell which bot moves next.

• 1. I don't think it needs a turn order: the only problem with adding simultaneous moves would be the need to account for ties. (You are going to run it more than once to pick a winner, right?) 2. I would keep the guess per turn without penalty for guessing wrong. A good strategy will allow a team to win before anyone wins by blind guessing. Too harsh a penalty for bad guesses will bias the game too much in favour of the last person to update their bot so that it fakes the responses of other teams. Nov 11 '14 at 10:43
• The idea is quite amusing, but something tells me there must exist a not too hard to find optimal strategy to maximize the chances of winning. The fight would likely occur around sending fake messages to the competitors. Second problem I see is, the first contestants will be at a huge disadvantage since the new players will see exactly how their code works. So much for secrecy. I think the challenge would be more interesting if the code was kept secret, but this is hardly compatible with the spirit of this site.
– user16991
Jan 24 '15 at 6:48
• @PhiNotPi are you still interested in this challenge? Would you be willing to allow me to implement this? Jul 29 '16 at 20:23
• @RohanJhunjhunwala Sure, you can implement this. I don't think I ever started on a controller for it, mainly because I don't think this challenge will be as fun in practice as in theory. Jul 30 '16 at 13:17

# Solve the Nonogram!

It is time to embark on a perilous quest to defeat the British Intelligence. The aim of this challenge is to write the shortest code that will solve a Nonogram.

# What is a Nonogram?

The rules are simple. You have a grid of squares, which must be either filled in black or left blank. Beside each row of the grid are listed the lengths of the runs of black squares on that row. Above each column are listed the lengths of the runs of black squares in that column. Your aim is to find all black squares. In this puzzle type, the numbers are a form of discrete tomography that measures how many unbroken lines of filled-in squares there are in any given row or column. For example, a clue of "4 8 3" would mean there are sets of four, eight, and three filled squares, in that order, with at least one blank square between successive groups. [1][2]

So the solution to the above Nonogram would be:

# Implementation Details

You can chose to represent the Nonogram however you would like and take it as an input in whatever way you deem fit for your language. Same goes for output. The aim of this challenge is to literally just get the job done; if you can solve the monogram with whatever output your program gives, that is valid. One caveat is you can't use an online solver :)

You are, of course, free to use any language you want and since this is code golf, the entries will be sorted in the order: accuracy -> length of code -> speed.

This problem is very algorithmically challenging in that there is no completely efficient solution to it and as such, you won't be penalized for not being able to solve larger ones, although your answer will be heavily rewarded if it is able to handle big cases (see bonus). As a benchmark, my solution works for up to roughly 50x50 within 5-10 mins.

# Bonus

I actually learnt about Nonograms from a cryptographic Christmas card released by the British Intelligence here. The first part was basically a massive 25x25 Nonogram. If your solution is able to solve this, you will get kudos :)

To make your life easier in terms of data entry, I have provided how I represented the data for this specific puzzle for your free use. The first 25 lines are the row clues, followed by a '-' separator line, followed by 25 lines of the col clues, followed by a '#' separator line, and then a representation of the grid with the square clues filled in.

7 3 1 1 7
1 1 2 2 1 1
1 3 1 3 1 1 3 1
1 3 1 1 6 1 3 1
1 3 1 5 2 1 3 1
1 1 2 1 1
7 1 1 1 1 1 7
3 3
1 2 3 1 1 3 1 1 2
1 1 3 2 1 1
4 1 4 2 1 2
1 1 1 1 1 4 1 3
2 1 1 1 2 5
3 2 2 6 3 1
1 9 1 1 2 1
2 1 2 2 3 1
3 1 1 1 1 5 1
1 2 2 5
7 1 2 1 1 1 3
1 1 2 1 2 2 1
1 3 1 4 5 1
1 3 1 3 10 2
1 3 1 1 6 6
1 1 2 1 1 2
7 2 1 2 5
-
7 2 1 1 7
1 1 2 2 1 1
1 3 1 3 1 3 1 3 1
1 3 1 1 5 1 3 1
1 3 1 1 4 1 3 1
1 1 1 2 1 1
7 1 1 1 1 1 7
1 1 3
2 1 2 1 8 2 1
2 2 1 2 1 1 1 2
1 7 3 2 1
1 2 3 1 1 1 1 1
4 1 1 2 6
3 3 1 1 1 3 1
1 2 5 2 2
2 2 1 1 1 1 1 2 1
1 3 3 2 1 8 1
6 2 1
7 1 4 1 1 3
1 1 1 1 4
1 3 1 3 7 1
1 3 1 1 1 2 1 1 4
1 3 1 4 3 3
1 1 2 2 2 6 1
7 1 3 2 1 1
#
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 1 1 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 1 1 0 0 1 0 0 0 1 1 0 0 1 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 1 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 1 1 0 0 0 0 1 1 0 0 0 0 1 0 0 0 0 1 1 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0


# There can be only 1!

Your task is, given a positive integer n, to generate an expression that equals to the number n.

The catch is: you're only allowed the number 1 in the output.

The operators at your disposal are:

• +, -, * and /
• sqrt (as s)
• ceil and floor (as c and f respectively)
• ! (factorial)
• The factorial, in this case, only works for positive integers.

You are also allowed to stack 1's together, so something like 11 is acceptable in the output. However, they count as the same amount of 1's that's in the number (so 11 counts as 2 1's).

You must also include brackets in the output, so that the expression in the output, when executed through the order of operations, will result in the input.

## Examples:

• Input = 24, one possible output = (1+1+1+1)!
• Input = 11, one possible output = 11
• Input = 5, one possible output = c(s((1+1+1+1)!))
• The ceiling of the square root of 24 is 5.

## Rules:

• You are guaranteed that the input is a positive integer from 1 to 2^31-1.
• Your program must work for any positive integer up to 2^31-1, even if they are not tested.
• Your program must finish processing all outputs for all numbers in the set in 1 hour.
• The results for every run of the program must be exactly the same - also, no seeds.
• You are not allowed to have imaginary numbers anywhere in the output (so no s(some negative number)).
• You are also not allowed to have numbers larger than 2^31-1 anywhere in the output, even when they are sqrted or /ed (so no (((1+1+1)!)!)! or ((1+1+1+1)!)!).

## Set of Numbers:

945536, 16878234, 32608778, 42017515, 48950830, 51483452, 52970263, 54278649, 63636656, 78817406, 89918907, 90757642, 95364861, 102706605, 113965374, 122448605, 126594161, 148064959, 150735075, 154382918, 172057472, 192280850, 194713795, 207721209, 220946392, 225230299, 227043979, 241011012, 248906099, 249796314, 250546528, 258452706, 276862988, 277140688, 280158490, 286074562, 308946627, 310972897, 322612091, 324445400, 336060042, 346729632, 349428326, 352769482, 363039453, 363851029, 392168304, 401975104, 407890409, 407971913, 425780757, 459441559, 465592122, 475898732, 482826596, 484263150, 506235403, 548951531, 554295842, 580536366, 587051904, 588265985, 588298051, 590968352, 601194306, 607771869, 618578932, 626776380, 667919873, 681786366, 689854904, 692055400, 697665495, 711608194, 734027104, 750869335, 757710567, 759967747, 777616154, 830071127, 833809927, 835873060, 836438554, 836945593, 863728236, 864158514, 871273503, 881615667, 891619600, 897181691, 918159061, 920521050, 924502226, 929983535, 943162304, 950210939, 950214176, 962610357, 974842859, 988572832


(These are 100 random numbers from 1 to 1 billion.)

## Scoring System:

Your score is determined like so:

• Your program will be tested against the random numbers in the set.
• You must provide the output generated using the numbers random numbers in the set (either inside your answer or as a pastebin link).
• Your then have two "scores": A primary score and a secondary score.
• Your primary score is (no. of 1's in output)*(no. of operators in output). If your primary score is the lowest, you win.
• Your secondary score is your byte-count, and is only used in the case of a tie-breaker - the person with the lowest byte-count wins.

## Meta:

• Anything that I need to clear up?
• Is this challenge a dupe?
• Is implicit multiplication allowed? Sep 11 '16 at 1:23
• @LegionMammal978 No, it is not allowed. You must use *. Sep 11 '16 at 1:43
• For the tiebreak, do parentheses contribute to the operator count? Sep 11 '16 at 1:49
• Does the code need to be deterministic (that is, do random algorithms need to set the PRNG seed to ensure the same results each time)? Sep 11 '16 at 1:51
• Surely at least one output must be hardcoded? Sep 11 '16 at 4:45
• Related, though I don't believe it's a dupe. Sep 11 '16 at 8:47
• code-challenge can't be used along with other scoring tags. Sep 11 '16 at 11:18

# Telegraphy Golf: Decode Baudot Code

## Background

In 1870 Émile Baudot invented Baudot Code, a fixed-length character encoding for telegraphy. He designed the code to be entered from a manual keyboard with just five keys; two operated with the left hand and three with the right:

The right index, middle and ring fingers operate the I, II, and III keys, respectively, and the left index and middle fingers operate IV and . (Henceforth I'll use their Western Arabic numerals, i.e. 1, through 5.) Characters are entered as chords. To enter the letter "C," for example, the operator presses the 1, 3, and 4 keys simultaneously, whereupon a rotating brush arm reads each key in sequence and transmits a current or, for keys not depressed, no current. The result is, in modern terms, a 5-bit least-significant-bit-first binary encoding, in which our example, "C," is encoded as 10110.

### 5 bits??

You might be thinking that 5 bits, which can express at most 32 unique symbols, isn't enough for even all of the English letters and numerals, to say nothing of punctuation. Baudot had a trick up his sleeve, though: His character set is actually two distinct sets: Letters and Figures, and he defined two special codes to switch between them. Letter Shift, which switches to Letters mode, is activated by pressing the 5 key alone (00001), and Figure Shift is activated with the 4 key (00010).

## Challenge

Your challenge is to write a program or function that decodes Baudot Code transmissions.

A real transmission would begin with some initialization bits, plus a start and stop bit before and after each character, but we're going to skip those and only worry about the 5 unique bits for each character. Input and output formats are discussed below.

### Baudot's Code

There are two different versions of Baudot Code: Continental and U.K. We're going use the U.K. version, which doesn't include characters like "É" from Baudot's native French. We're also going to leave out all of the symbols in the U.K. version that aren't among the printable ASCII characters. You will only have to decode the characters in the table below, all of which are printable ASCII characters except the final three control characters that are explained below the table.

The "Ltr" column shows the characters in Letter mode and "Fig" shows the Figure mode characters:

        Encoding             Encoding
Ltr Fig  12345       Ltr Fig  12345
--- --- --------     --- --- --------
A   1   10000        P   +   11111
B   8   00110        Q   /   10111
C   9   10110        R   -   00111
D   0   11110        S       00101
E   2   01000        T       10101
F       01110        U   4   10100
G   7   01010        V   '   11101
H       11010        W   ?   01101
I       01100        X       01001
J   6   10010        Y   3   00100
K   (   10011        Z   :   11001
L   =   11011        -   .   10001
M   )   01011        ER  ER  00011
N       01111        SP  FS  00010
O   5   11100        LS  SP  00001
/       11000


The last three rows in the right column are control characters:

• ER is Erasure. Baudot's telegraphy machines would print an asterisk-like symbol for this character to tell the reader that the preceding character should be ignored, but we're going to be even nicer to the reader and actually omit (do not print) the preceding character. It acts the same in both Letter and Figure mode.

• FS is Figure Shift. This switches the character set from Letters to Figures. If the decoder is already in Figure mode, FS is treated as a Space (ergo SP in the "Ltr" column). When the decoder is in Figure mode it stays in Figure mode until an LS character is received.

• LS is Letter Shift. It switches the character set from Figures to Letters. If the decoder is already in Letter mode, LS is treated as a Space. When in Letter mode the decoder stays in Letter mode until an FS character is received.

The decoder always starts in Letter mode.

Here's an example with Figure Shift, Letter Shift, and Space:

01011 10000 00100 00001 00010 10000 11100 00001 10101 11010
M     A     Y   LS/SP FS/SP   1     5   LS/SP   T     H


This yields the message MAY 15TH. As you can see, the first 00001 (Letter Shift/Space) character acts as a space, because the decoder is already in Letter mode. The next character, 00010 (Figure Shift/Space) switches the decoder to Figure mode to print 15. Then 00001 appears again, but this time it acts as Letter Shift to put the decoder back in Letter mode.

For your convenience, here are the characters in a format that's perhaps easier to digest in an editor, sorted by code:

A,1,10000|E,2,01000|/,,11000|Y,3,00100|U,4,10100|I,,01100|O,5,11100|SP,FS,00010|J,6,10010|G,7,01010|H,,11010|B,8,00110|C,9,10110|F,,01110|D,0,11110|LS,SP,00001|-,.,10001|X,,01001|Z,:,11001|S,,00101|T,,10101|W,?,01101|V,',11101|ER,ER,00011|K,(,10011|M,),01011|L,=,11011|R,-,00111|Q,/,10111|N,,01111|P,+,11111


### Input

Input will be a string, array, or list of bits in least-significant-bit-first order. Each character will be represented by a quintet of 5 bits. Bits may be in any reasonable format, e.g. a binary string, an array of 0s and 1s, a string of "0" and "1" characters, a single very large number, etc., as long as it maps directly to the bits of the transmission.

Every transmission will have at least one printable quintet and at most 255 quintets (printable or otherwise), i.e. 5–1,275 bits inclusive.

The input can contain only the bits of the transmission, with two allowed exceptions: Any number of leading or trailing 0 bits and/or, for string input, a single trailing newline may be added to the transmission. Leading or trailing bits or characters cannot be added before or after each quintet, i.e. you cannot pad each quintet to 8 bits or separate quintets with any additional bits, e.g. "01111\n11100".

Notes & edge cases
1. The transmission will contain only the characters in the "Ltr" and "Fig" columns in the table above. You will never receive e.g. 01110 in Figure mode, because it is absent from the "Fig" column.

2. It is assumed that the decoder will always be in Letter mode at the beginning of a transmission. However, the first character may be an FS character to switch to Figure mode immediately.

3. When the decoder is in Letter mode, it may receive an LS character, and when it is in Figure mode it may receive an FS character. In either event a Space character must be printed (see Output).

4. The ER character will never be the first character in a transmission, nor will it ever immediately follow an LS, FS, or another ER.

5. An FS character may immediately follow an LS character and vice versa.

6. Neither the LS nor FS character will be the last character in any transmission.

7. The / and - characters may be received in either Letter mode (codes 11000 and 10001, respectively) or Figure mode (10111 and 00111).

### Output

Output may be in any reasonable format, the most reasonable being ASCII (or UTF-8, for which all of the represented characters are the same as ASCII). Please indicate in your answer if your output is in another encoding or format.

Notes
• The space character (see 3. above) should be an ASCII space (0x20) or your encoding's equivalent, i.e. what you get when you press the space bar.

## Winning

This is code golf. The shortest code in bytes wins.

## Restrictions

• Standard loopholes are forbidden.

• Trailing spaces and/or a single trailing newline are allowed. Leading spaces or other characters (that are not part of the transmission) are disallowed.

• You may not use any built-in or library functions that decode Baudot Code (or any of its descendants, e.g. Murray Code, ITA-1, etc.).

## Test Cases

Input: 001101000010100111101110010101
Output: BAUDOT

Input: 11010010001001100011110111101111100
Output: HELLO

Input: 01011100000010000001000101000011100000011010111010
Output: MAY 15TH

Input: 00010001000001000001011101110011100101010010110101010001111100101
Output: 32 FOOTSTEPS

Input: 10110000110101011100111100001111011010000001101110
Output: GOLF

Input: 000100011000001111100000100010110111001100010110010000111111
Output: 8D =( :P

Input: 0000100001000010000100010001111011111011000011100010001

• This is quite similar to the Morse decoding question. The main thing it adds is the three control characters. It might be worth adding a cross-reference in a comment after posting the question. Sep 19 '16 at 21:56
• Can the transmission start with erasure? Sep 20 '16 at 1:00
• @Sp3000 No. Good catch. I had a note to that effect but apparently accidentally deleted it. Sep 20 '16 at 1:07
• Can an erasure follow a shift that is acting as a space? Sep 20 '16 at 14:16
• @Phlarx Nope. ER will never follow LS or FS. Sep 20 '16 at 14:17
• Thank you for your feedback, all. I've posted the challenge: codegolf.stackexchange.com/questions/94056/… Sep 21 '16 at 13:23
• Don't forget to take of this answer in the Sandbox. " When you think your challenge is ready for the public, go ahead and post it, replace the post here with a link to the challenge and delete it. " Sep 22 '16 at 19:29

my first post on here, be gentle ;)

# Find all anagrams within a text

Somehow I stumbled upon an implementation of a school assignment from about a year ago, and after having seen many amazing and mindblowing code-golf solutions on here, I thought it's time I bring my own challenge and see how much you guys can blow my mind again ;)

## The assignment

Given a text, find all words that have at least one other word in the text as an anagram (case insensitive). Multiple occurrences of the same word are not counted.

The output shall be grouped by words that are an anagram of each other.

## Rules

• How you handle input/output is up to you. Function-parameters, file-io, standard in/out, whatever works the best for you.
• You must be able handle any non-empty input as long as you don't run into language or memory limitations.
• The output does not have any fixed formatting. That means you may put them each group at a line, or put them all at one line but use different delimiters, a 2d array, some other exotic data-structure your language of choice happens to have, as long as it makes reasonable sense, it is considered correct. (This means that for example if you are just writing a function, that function does not need to display the output, it could just provide it as a return-value.) Just keep in mind the requirement that the words that are an anagram of each other should be grouped together.
• The order in which the output appears does not matter. That applies to the order of the groups as well as the order of the words within the group.
• A group of only one word is invalid, since that fails the "have at least one other word in the text as an anagram" requirement. (just omit them from your output ^^)
• Each word should only appear once in the output
• All interpunction characters are stripped away from the word before checking for anagrams. That means that "it's" and "its" are the same word (and thus both are an anagram of "sit"). My sample program at the bottom uses http://en.cppreference.com/w/cpp/string/byte/ispunct as check if a character is an interpuntion character. If your language has such a method, you may use it. Otherwise take the characters from the default C locale as specified on there:

!"#$%&'()*+,-./:;<=>?@[\]^_{|}~ • All other characters are part of the word and treated as is, so "a" and "á" are not the same. ## Example Given the following input text (the actual text I was given as example by school :P, no idea where this text is coming from...) Parts of the world have sunlight for close to 24 hours during summer. Dan went to the north pole to lead an expedition during summer. He had a strap on his head to identify himself as the leader. Dan had to deal with the sun never going down for 42 consecutive days and his leadership strap soon became a blindfold. He wondered what kind of traps lay ahead of him. the following output would be correct: • 24, 42 • deal, lead • and, dan • parts, strap, traps Or this would also be correct: 24, 42 | deal, lead | and, dan | parts, strap, traps This one would not 24, 42 , deal, lead , and, dan , parts, strap, traps (since the groups are not obvious) ## My own (non golfed) version to check The is the exact program I submitted to school back then. You may use it to check your own results. Added bonus: If it happens to be that this program has a bug (I haven't found them yet) your submission is allowed to have it as well, since it is used to check the result. (In that case you are of course not required to have said bugs) #include <string> #include <iostream> #include <fstream> #include <map> #include <set> #include <algorithm> #include <cstring> void stringRemoveInterpunction(std::string& string); void stringToLower(std::string& string); std::string stringToAnagramIdentifier(std::string word); /** * due to use of std::ispunct and std::tolower it may not work for text with non-ascii characters??! */ int main(int argc, char* argv[]) { if (argc < 2) { std::cerr << "usage: " << argv[0] << " <filename>" << std::endl; return 1; } std::ifstream fileStream(argv[1]); if (!fileStream) { std::cerr << "Could not open file " << argv[1] << std::endl; return 2; } // map to store the anagrams, key is so called "anagram identifier", value is a list of the words. std::map<std::string, std::set<std::string>> anagrams; // read words separated by whitespace from the file for (std::string word; fileStream >> word;) { // remove interpunction & convert to lowercase, since casing should be ignored stringRemoveInterpunction(word); stringToLower(word); // add to anagrams-store anagrams[stringToAnagramIdentifier(word)].insert(word); } // display all the anagrams for (auto anagram : anagrams) { // skip entries which contains only one item, no anagrams found if (anagram.second.size() <= 1) { continue; } // output a comma-separated list of the anagrams auto anagramIterator = anagram.second.begin(); std::cout << *anagramIterator++; while (anagramIterator != anagram.second.end()) { std::cout << ", " << *anagramIterator++; } std::cout << std::endl; } return 0; } void stringRemoveInterpunction(std::string& string) { string.erase(std::remove_if(string.begin(), string.end(), std::ptr_fun<int, int>(&ispunct)), string.end()); } void stringToLower(std::string& string) { std::transform(string.begin(), string.end(), string.begin(), std::ptr_fun<int, int>(&std::tolower)); } std::string stringToAnagramIdentifier(std::string word) { // sort the characters std::sort(word.begin(), word.end()); return word; }  # Sandbox Questions • Do i need to add other tags, or is just code-golf enough? • I'm not completely sure about the upper-limit of the input text. My idea was that the code should be able to handle any size input as long as its within the memory-limits of the language. Like you don't have to write "memory optimal code" or something, but also shouldn't asume it is smaller than X. I could also just pick an upper limit of "1 kilobyte" or something to avoid any uncertainty about the requirements I think this is fine now as it is. • Someone in the comments below asked how to handle special characters like$?() so I took a look at how my "check program" handled that and it strips them away before doing the anagram check. So I added a rule for that, but while writing that I felt it makes it needlessly complicated and I'm considering ditching that rule and altering my check-program to reflect that (but then I cant claim its the exact same anymore :( )
• Any other parts that are not clear?
• What happens if there are 3 that are anagrams, such as eat ate tea? Are they all printed in one line / group? Dec 19 '16 at 17:27
• @Flp.Tkc yes, like "parts, strap, traps" in the example Dec 19 '16 at 17:29
• I suggest you remove the grouping rule, since it's not really the interesting part of the challenge. It just adds code and limits the solutions. It's apparent which of the words that are together anyway. I do suggest they have to be grouped though, but without the need for delimiters. Dec 20 '16 at 23:24
• I think the memory rule is fine. I'm quite sure people will write a script that in theory would work for any input length if it wasn't for language or memory limitations. I also suggest you guarantee at least one character in the input. Otherwise people would need to add code just to handle empty input and that's not the interesting part of the challenge. Dec 20 '16 at 23:29
• You should add rules regarding special characters. Are it's, sit and its anagrams? What about hyphens? Can there be any special characters such as $?() etc? How are they treated? Dec 20 '16 at 23:31 • @StewieGriffin The grouping thing is a natural result of my solution to the problem back then, and imo its a fun part of the challenge, so I'm not totally sure about removing it. About the memory limit: I'm totally fine with the guarantee of at least one character if you think empty input needs special handling (i didnt think it would, but I dont really care :P) And yes, you are correct about special characters. I'd say "it's" is two words: "it" and "s". All special characters are ignored, so essentially regarded as whitespace between words. I'll add that Dec 20 '16 at 23:35 • welp, turns out I handled special characters differently, I strip them away from the word, so "it's" becomes "its", guess that'll be the rule then since I want to keep as close as possible to the original program Dec 20 '16 at 23:48 • @StewieGriffin I added a rule about special character handling, but I'm not completely sure about it, thoughts? (see my added "sandbox question") Dec 21 '16 at 0:05 • parsing and anagrams are relevant tags, maybe strings too, but I'm not sure about that one. Dec 21 '16 at 7:43 • !"#$%&'()*+,-./:;<=>?@[]^_{|}~ are all the non-alphanumeric ASCII-characters, except \ . I suggest you include the missing two symbols in the list to ignore, and say: "All non-alphanumeric characters (except spaces and newlines) must be trimmed away. So, it's and its are the same word." (You might want to rephrase that since my English isn't perfect, but something along those lines. If this is the rule then R2D2 and dr.22 will be anagrams, I'm not sure if that the desired behavior..? Dec 21 '16 at 10:17
• PS! I don't mean to be difficult, it's just that in my experience you'll get these questions sooner or later. So it's a good thing to sort it out while it's still in the Sandbox :) Dec 21 '16 at 10:20
• @StewieGriffin those two characters should have been included, look at the list from en.cppreference.com/w/cpp/string/byte/ispunct where I got it from, somehow I messed up the copy-paste :( And about "what is desired behaviour?" Im honestly not sure, I never really thought about it before you mentioned it and then I looked at how my sample program handled it. I remember putting in the ispunct-trim for stuff like commas after a word, im not sure about characters within the word... Dec 21 '16 at 10:26
• You can say that the input will not have any special characters except ' and -. Those two must be trimmed away. I think you must include those two, since these can be found in many texts. Dec 21 '16 at 10:34

# PPCG Handwriting OCR code-challengetest-battery

(insert logo here once I make it)

Given an image consisting of handwritten text, output the text that is written. The image of the handwritten text will be generated by taking characters from one or more handwriting samples given by PPCG users.

## Rules

• You may not hardcode your program to only recognize the samples in the corpus.
• There will be sufficient spacing between characters to avoid ambiguity.
• Only ASCII alphanumeric characters (those matching the regex [A-Za-z0-9], i.e. uppercase and lowercase English letters and digits) will be present in the input.
• Inputs will be formed by concatenating individual characters from the handwriting samples.
• The test cases used for scoring may be modified at any point if I feel it is necessary to do so. Reasons may include but are not limited to: needing more test cases to have a single winner, removing problematic test cases, and fixing errors in test cases.

Aside from the above considerations, there are no guarantees on the appearance of the handwriting, as these are actual handwriting samples and thus can have drastic variances.

## Score

Your score will be the number of test cases that are correctly recognized, divided by the total number of test cases. The highest score wins. In the event of a tie, the first submission to reach the high score wins. Additional test cases may be added to break ties.

## Handwriting Samples

This Imgur album contains the handwriting samples, as well as the names of the users who contributed them.

I've made a chat room for submitting handwriting samples. The more samples I get, the better this challenge will be, so please take a few minutes and submit a sample!

• You may not hardcode your program to only recognize the samples in the corpus.: Can we tailor our code to be better for the samples than other inputs though? Aug 2 '17 at 16:08
• The test cases used for scoring may be modified at any point: Will current answers be modified? Aug 2 '17 at 16:09
• @TheLethalCoder 1) No. 2) Answers will be run on the test cases any time the answer or the test cases change, and the scores will be updated accordingly.
– user45941
Aug 2 '17 at 16:11
• Hadn't seen that loophole before :) Aug 2 '17 at 16:13
• Can I nitpick again and say handwriting OCR is called ICR? :P Aug 3 '17 at 9:06
• Can you add an example input as well? Aug 3 '17 at 9:07
• @TheLethalCoder 1) ICR is when a program tries to learn what handwriting looks like via machine learning. OCR is just parsing written/text input into data. This is OCR, not ICR. 2) I'll add some examples once I get more samples and finish writing my generator.
– user45941
Aug 3 '17 at 9:08
• Can you assume a minimum height for the characters? Aug 3 '17 at 9:28
• @TheLethalCoder Aside from the above considerations, there are no guarantees on the appearance of the handwriting, as these are actual handwriting samples and thus can have drastic variances.
– user45941
Aug 3 '17 at 9:29
• To be honest with no restrictions this is going to be very hard, Do you lose points for returning extra information? Assume the input Hello if I return H.e.l.l.o. is that 100% for that test case or do I lose and get something like 50%? Aug 3 '17 at 9:31
• And does the output have to be in the correct order? Aug 3 '17 at 9:58
• @TheLethalCoder It's all or nothing. Getting 100% on a test battery challenge should be hard.
– user45941
Aug 3 '17 at 9:58
• Please update imgur album Sep 18 '17 at 4:28
• @Pavel I will once I finish cutting up the images. My free time has been limited these past few weeks.
– user45941
Sep 18 '17 at 4:29

## 2 Spooky 4 Me

In terms of halloween, some things are just too spooky for me... Feel like we need some serious doots from skeletons to fuel our hallowed weens. So, in the spirit of that end, print the following, exactly as it is shown, if and only if the input does not equal "DOOT" (in all caps ONLY):

               _.---._
.'       '.
:)       (:
\ (@) (@) /
\   A   /
)     (
\"""""/
'._.'
.=.
.---._.-.=.-._.---.
/ ':-(_.-: :-._)-:' \
/ /' (__.-: :-.__) '\ \
/ /  (___.-' '-.___)  \ \
/ /   (___.-'^'-.___)   \ \
/ /    (___.-'='-.___)    \ \
/ /     (____.'='.____)     \ \
/ /       (___.'='.___)       \ \
(_.:       '---'.=.'---'       :._)
:||        __  _.=._  __        ||:
:||       (  '.-.=.-.'  )       ||:
:||       \    '.=.'    /       ||:
:||        \    .=.    /        ||:
:||       .-'.'-._.-'.'-.       ||:
.:::\      ( ,): O O :(, )      /:::.
|||| '     / /''--'--''\ \     ' ||||
''''      / /           \ \      ''''
/ /             \ \
/ /               \ \
/ /                 \ \
/ /                   \ \
/ /                     \ \
/.'                       '.\
(_)'                       '(_)
\\.                       .//
\\.                     .//
\\.                   .//
\\.                 .//
\\.               .//
\\.             .//
\\.           .//
///)         (\\\
,///'           '\\\,
///'               '\\\
""'                   '""


However, if the input DOES equal "DOOT", in all caps only, print this instead:

               _.---._
.'       '.
:)       (:
\ (@) (@) /
\   A   /
)     (
\"""""/
'._.'          ' ''''    _''|
.=.       @=====***===::_  |
.---._.-.=.-._.---. (( \-@|_) )) .|
/ ':-(_.-: :-._)-:' \ ]--------'"
/ /' (__.-: :-.__) '\ \   ||:
/ /  (___.-' '-.___)  \ \  ||:
/ /   (___.-'^'-.___)   \ \ ||:
/ /    (___.-'='-.___)    \ \||:
/ /     (____.'='.____)     \ ||:
/ /       (___.'='.___)       \||:
(_.:       '---'.=.'---'       :._)
:||        __  _.=._  __
:||       (  '.-.=.-.'  )
:||       \    '.=.'    /
:||        \    .=.    /
:||       .-'.'-._.-'.'-.
.:::\      ( ,): O O :(, )
|||| '     / /''--'--''\ \
''''      / /           \ \
/ /             \ \
/ /               \ \
/ /                 \ \
/ /                   \ \
/ /                     \ \
/.'                       '.\
(_)'                       '(_)
\\.                       .//
\\.                     .//
\\.                   .//
\\.                 .//
\\.               .//
\\.             .//
\\.           .//
///)         (\\\
,///'           '\\\,
///'               '\\\
""'                   '""


# Rules

• Trailing newlines and spaces are allowed.
• The design is horizontally symmetric, if you find inconsistencies let me know.

Doot it up, and enjoy!

(Yes, I'm going to make it more official when posting on the actual SE)

• What about this challenge ensures that the same old techniques won't be the best ones (i.e. that it adds value to the site)? Oct 13 '17 at 23:01
• @PeterTaylor worse? Better? 10x worse? 10x better? I don't really know what makes the challenge unique beyond a formal proof that it is, but if the users enjoy it; why not allow it... current event challenges attract new users. Oct 16 '17 at 23:03

# Check equation proofs in a ring

The recent to prove that (-a)×(-a) = a×a attracted a number of faulty submissions, because there wasn't an easy way to verify the proofs. So, let's write some proof checkers.

### Input

Your program should take a sequence of strings representing expressions in a ring. Valid expressions consist of:

• Single-lowercase-letter variables (a to z)
• Two constants: the additive identity 0 and multiplicative identity 1
• Compound expressions: (X+Y), (X*Y) and (-X), where X and Y stand for subexpressions. (The parentheses must always be present, and there must be no whitespace.)

• All strings except the first and last represent valid expressions.
• Each expression (after the first) can be obtained from the preceding expression, by substituting one of the ring axioms in the expression exactly once.

Output truthy if these conditions are met. Otherwise, output falsey.

You may assume that the first and last strings in the input are valid expressions. But your program must check the intermediate strings.

### The ring axioms

For this challenge, use the following substitution rules (and do not use any others). Substitutions can go both left-to-right and right-to-left.

1. (X+(Y+Z)) = ((X+Y)+Z)

2. (X+0) = X

3. (X+(-X)) = 0

4. (X+Y) = (Y+X)

5. (X*(Y*Z)) = ((X*Y)*Z)

6. (X*1) = X

7. (1*X) = X

8. (X*(Y+Z)) = ((X*Y)+(X*Z))

9. ((X+Y)*Z) = ((X*Z)+(Y*Z))

## Scoring

Proof checkers are traditionally small, so that people can review them easily. Therefore, your program should be written in as few bytes as possible.

Is the input format fair for most languages and approaches?

Usually, code-golf problems should not require input validation. However, I thought it would be appropriate behaviour for a proof checker. I think the current spec still accommodates regex-based solutions.

The format for the original challenge also listed which axiom was used for each step. I could include this but I doubt that it improves the challenge much.

## Test cases

### Valid proofs

(0+a)
(a+0)
a


(a*(-1))
((a*(-1))+0)
((a*(-1))+(a+(-a)))
(((a*(-1))+a)+(-a))
(((a*(-1))+(a*1))+(-a))
((a*((-1)+1))+(-a))
((a*(1+(-1)))+(-a))
((a*0)+(-a))


### Invalid proofs

These proofs are missing intermediate steps.

(0+a)
a


(-0)
((-0)+0)
0


((a*0)+(-a))
(0+(-a))


This is simply untrue, so no proof should ever be accepted.

(a*b)
(b*a)


### Invalid expressions

Your proof checker should reject if these appear partway through a proof.

a+b


(a+-b)


(a + b)


1+


42

• You should include the ring axioms to make the post self-contained. Oct 18 '17 at 16:23

At the ASCII Stock Exchange, each character has a price. If a character is used more often, its price rises, otherwise the price decreases over time.

Initially, each character has price 10. [Meta: Is this too low/high?] After each answer, the prices change as follows:

• Each character that is not used in the answer's code has its price decreased by one, except when the price is already one, in which case it stays one.
• If a character is used n-times, then its price increases by n.

We define the score of a piece of code as the sum of the prices of its characters.

### Example

For the sake of simplicity, we only consider characters A, B and C for this example. The challenge itself works with all bytes from \0 to \255. Initially, we have the following prices:

A -> 10, B -> 10, C -> 10


If the code of the first answer is BAAA, then is has a score of 40 (computed by taking the previous character prices into account) and the prices change to

A -> 13, B -> 11, C -> 9


If the next answer is CC, it has a score of 18 and the prices are updated to

A -> 12, B -> 10, C -> 11


Your objective is to write a program or function which calculates the score of a given piece of code in dependence of a list of previous answers which all influence the initial prices in the way described above.

The goal is to do so while minimizing the submission's score itself in the context of this challenge, that is your submission should be able to calculate its own score by taking a list of all previous submissions and its own source code as input.

The answer with the lowest score in each language wins.

## Rules

• You may take a list of strings and a string as input, or require that the string to be scored is the first/last element of the list, or any other reasonable input format.
• You may not answer twice in a row.
• If an answer in language X has already been posted, you may only post another answer in language X if your submission achieves a lower score than the previous answer and the code is not identical.
• For this challenge only major releases of languages are considered their own language (e.g. Java 7 vs. Java 8). If there already is an answer in version A of a language and you have an answer in version B of the language and are in doubt whether version B is different enough from version A to be treated as different language, make sure that your code is not valid in version A.

To avoid having to copy all previous answers in order to calculate your submission's score, the chain will maintain a score calculator on TIO. Click on the link to the calculator in the previous answer and enter your code into the input field to calculate its score. Then add your code as a command-line argument, generate a new link and include it in your answer for the next submission.

If you wrote answer number 42 in Haskell with a score of 100, please format it as

 <code>


## Test Cases

These test cases are in the format list of strings, string to score -> result.

[], "BAAA" -> 40
["BAAA"], "CC" -> 18
["abc"], "abc" -> 33
["ab12", "aa22", "31a"], "ac23" -> 42
["a","b","c","d","e","f","g","h","i","j"], "123" -> 3


## Meta

• Any idea what could be a good initial price? I picked the number 10 rather arbitrarily.
• Letting the cost of unused characters decrease until 0 might lead to score 0 answers. Do you think this is a problem and the minimum cost should be 1? Minimum changed to 1.
• I'm unsure what range of characters is a sensible choice. Limiting answers to printable ASCII plus white space would make things easier but also exclude a lot of languages. Another possibility would be to allow the whole byte range from \0 to \255. Then also golfing languages could participate, albeit to score them they would need to be converted to their byte form which usually contains a lot of unprintable characters. The score calculator is able to handle unprintables, but I don't know how to insert them into the text fields on TIO. All bytes from \0 to '\255' are allowed.
• Is the winning criterion suitable for answer chaining?
• A leader board snippet would be nice, but I don't know how to modify the existing ones. If someone could provide such a snippet, I would be very grateful.
• Relevant tags?
• I think decreasing the scores to 1 is more sensible, because otherwise I could write a submission using all (or even just one of) the zero-score characters a billion times (say, in a comment), keeping a "minimum" score, but then subsequent submissions would have completely absurd scores, and it'd be easy to outgolf later, leading to a boring answer chain. Oct 2 '17 at 18:08
• You may want to correct "enter your code into the input field to calculate its score. Then add your code as a command-line argument," Oct 2 '17 at 19:55
• I think allowing all 256 bytes is a good idea because languages like Jelly, 05AB1E, etc. will more than likely use more than the printable ASCII chars. Oct 2 '17 at 20:30
• "While in principal Python 2.7.14 and Python 2.7.13 are different languages according to the site rules, I recommend to avoid using the fact that it is technically allowed as an excuse to post boring answers." Recommendations do not work, especially when they're as imprecise as this. (Are you "recommending" not treating Python 2 and Python 3 as separate languages? I have no idea). If you want to ban boring exploitation of the convention on different interpreters, ban it outright, but give a clear definition of how lines should be drawn. Oct 2 '17 at 21:21

Note: If you are seeing this first, you might want to sort by active.

## Unhappy numbers ascii art

Draw a square (or a rectangle as close to a square as possible) that represents the cycle of an unhappy number.

[ short description of unhappy numbers here + example ]

[ square formating rules ]

Unhappy integer.

ASCII art.

### Example

Input:
4
Output:
4 -  16 - 37
20         58
42 - 145 - 89

• The cycle of an unhappy number is a constant.
– J B
Mar 7 '11 at 23:42
• @JB: thanks, I will rephrase the question. I didn't mean the 4 cycle. (Why did I chose 4 as an example? :/ ) Mar 8 '11 at 4:56
• @Eelvex This is an nice challenge. Are you still interested in finishing it? Feb 7 '16 at 19:06
• This challenge proposal has been inactive for over a month. I would like to take ownership of the challenge and make it ready for posting. Please let me know within the next 2 weeks if you have any objections and would still like to finish and post this challenge yourself. Feb 10 '16 at 0:19
• @JAtkin, no objections. Feb 12 '16 at 11:20
• If this was posted, can you please delete it? Aug 17 '17 at 16:58

# Tower Builder king-of-the-hill

The king is coming to visit! Your city is competing with another neighboring city to attract his attention.

Each player owns their own tower within a city full of other players. Each turn you place 1 blocks on your tower or another tower in your city.

After 100 turns, the king will only visit the city with the highest tower. If he visits your city, then you will gain points equal to the number of blocks in your personal tower. In the case of a tie, neither city is visited.

Games include all players, and each game will randomly arrange players into cities. Your score is the total score across all games.

• Player identifiers are randomly generated at the start of the tournament, but are consistent from game to game.
• In addition, contrary to past KoTHs: I allow saving state from game to game (but not between tournaments)
• You will always have complete information, including:
• The size of everybody's towers (including the other city)
• The actions players have taken
• The current score of all players
• How is always playing on the tallest tower in your city a bad strategy? Maybe the other city will do the same, but you won't lose. Jul 22 '17 at 22:47
• @aschepler because the number of points you get is height of your personal tower. If you only build on another's tower, and never your own, you'll never get any points. Jul 23 '17 at 1:55
• @NathanMerrill it took me a few minutes to understand what you even meant by that. you probably need to make this more clear Aug 7 '17 at 0:24
• If the points are only awarded to the player who is visited by the king, it would seem that putting 99 blocks on the city tower and 1 block on your personal tower guarantees victory, no? Jan 30 '18 at 17:22
• @AdmBorkBork there's no singular "city tower". Furthermore, you are still competing against the players in your city. Your score is your total score across many games. Jan 30 '18 at 17:40
• Oh, the part that I missed was that multiple players share a city. I think that should be made more clear because that will drastically change strategy. I read it as you have a personal tower and everyone also gets their own city with a separate tower, and it's only the city's tower that matters for the king. Jan 30 '18 at 17:45
• This needs some clarification about arrangement. The game will randomly arrange players into one of () cities, or a city with () others in it
– pfg
Jan 30 '18 at 19:10
• @pfg It'll definitely be one of () cities, but I'm not sure how many. My intuition says "2", but I can't give a solid reason. Any suggestions? Jan 30 '18 at 19:21
• 2 or 3 per city or total cities? 3 seems good per city because with just two the strategy is much easier @Nathan Merrill
– pfg
Jan 30 '18 at 19:23
• Hmmm...I'm thinking 100 players in 2 cities, and allow for duplicate entries. Jan 30 '18 at 19:28
• It seems to me that if you allow saving state you can simplify the last point to "You will be notified of the actions of every player" and let those who want to analyse it calculate the sizes of the towers, scores, etc. Normally I would favour supplying calculated information to save the players from re-implementing the game logic, but here the logic is simpler than the serialisation would be. Jan 31 '18 at 8:43
• @PeterTaylor I already provide complete information about the current game (including its history). The difference here is that you are allowed to persist information from game to game, meaning you can remember players who are antagonistic. Jan 31 '18 at 15:04
• My point is that the communication between the server and the bots would be simpler if you didn't provide that information, and you don't need to provide it because it can be calculated easily. Jan 31 '18 at 15:07

# Chess ASCII Art, Knight

In honor of the world chess championship, in the shortest possible program, output the following ASCII art piece

      ,....,
,::::::<
,::/^\".
,::/,    e.
,::; |        '.
,::|  \___,-.  c)
;::|     \   '-'
;::|      \
;::|   _.=\
;:|.= _.=\
'|_.=   __\
\_..== /
.'.___.-'.
/          \
('--......--')
/'--......--'\
"--......--"


This is a code-golf challenge

• You might want to make sure all the lines are aligned properly (they could be fine, since I'm on mobile and I know it can display differently, but it looks bent to me). Nov 23 '18 at 19:59
• you're right, it was a little bent, I've reformatted it Nov 23 '18 at 20:17
• Seems straightforward enough Nov 24 '18 at 1:23
• lol, akin to image compression of pixel art in a very specific case :) I like the idea. Nov 24 '18 at 22:22
• The very worst is approx 145 bytes + "verbatim output this". Be fun to see much better ones :) Nov 24 '18 at 22:33
• Isn't the World Chess Championship already over? According to google it ended nov. 28th. ;) Did you forgot to post it? Dec 3 '18 at 9:08
• Yeah, I made this post on November 23rd, cross-posting from sandbox eventually slipped my mind Dec 3 '18 at 14:42
• @Thaufeki You could still post it, or are you going to wait a year? ;) Dec 4 '18 at 10:22
• I would have to wait two, next one isn't until 2020! I'll post it now Dec 4 '18 at 14:43

# Is this checkmate?

Input

A chess position in FEN format. You can assume the input is a valid chess position.

Output

Two distinct consistent outputs for checkmate or not.

Examples

8/8/8/8/8/5BKN/8/7k b - - 93 47
Mate

• I suggest wording similar to “two distinct consistent outputs for checkmate or not” Mar 12 '19 at 11:52
• @Quintec Thanks.
– user9207
Mar 12 '19 at 11:58
• I'd recommend keeping it all self-contained and having a description for the FFN format, as well as a few more test cases
– Jo King Mod
Mar 12 '19 at 21:41
• Is restricted to the FFN format a part of the challenge? Why not allow it in any reasonable format?
– tsh
Mar 13 '19 at 5:47
• @Quintec why not just say truthy or falsey?
– qwr
Jun 20 '19 at 14:48
• I suggest removing the restriction to FEN format, as it doesn't really add anything to the challenge, and specifying that the output be a truthy or falsey value as that is the usual spec for these types of challenges. Aug 26 '19 at 13:28

## Lexicographically earliest valid UTF-8 byte sequence permutation

There are currently 1,114,112 possible Unicode characters (code points). Each character has a unique valid byte sequence in the UTF-8 encoding. Different characters have different length encodings:

• ASCII characters have a 1-byte encoding 00-7F.
• The next 1920 characters have a 2-byte encoding C2 80-DF BF.
• The rest of the BMP has a 3-byte encoding E0 A0 80-ED 9F BF and EE 80 80-EF BF BF.
• The other planes have a 4-byte encoding F0 90 80 80-F4 8F BF BF.

It's possible for two strings (specific non-normalised sequences of Unicode code points) of Unicode to have byte sequences that are permutations of each other in a number of ways:

• One string could simply be a permutation of the other at the Unicode level, e.g. ab (61 62) and ba (62 61).
• UTF-8 continuation bytes could be switched between two characters, e.g. ¡â (C2 A1 C3 A2) and ¢á (C2 A2 C3 A1).
• UTF-8 continuation bytes could be switched within a character, e.g. ᴵ (E1 B4 B5) and ᵴ (E1 B5 B4).

For this challenge I would like you to write a program or function that finds the string whose UTF-8 byte sequence is lexicographically earliest of all such sequences that are permutations of the UTF-8 byte sequence of a given Unicode string.

For example, if your input is ᵴ¢ába (E1 B5 B4 C2 A2 C3 A1 62 61) your output would be ab¡âᴵ (61 62 C2 A1 C3 A2 E1 B4 B5).

Note however that some byte sequences are not valid UTF-8 (e.g. E0 80 A0 which is an overlong encoding for a space) so you need to take care to avoid these.

It would be helpful if your "Try It Online" or similar link includes a footer that helps demonstrate the correctness of your output, where this is not obvious from the I/O format or code.

This is , so the shortest program or function that breaks no standard loopholes wins!

• For test cases, it will probably be a good idea to provide both strings and hex since I'd guess many languages will have to try both. Also this probably needs at least a link to an explanation of UTF8 continuation bytes. Jun 29 '19 at 16:57
• "permutation of its canonical" should be "permutation of the input's canonical". Jun 29 '19 at 17:00
• @FryAmTheEggman ... but I provided the hex? I'm not sure what I'm missing...
– Neil
Jun 29 '19 at 23:24
• @EriktheOutgolfer How about "I would like you to write a program or function that returns the Unicode string whose canonical UTF-8 byte sequence is the lexicographically earliest of all such sequences that are permutations of the canonical UTF-8 byte sequence of a given Unicode string"?
– Neil
Jun 29 '19 at 23:27
• I meant in the example that you actually had, and presumably some number of test cases. I only mentioned it because I thought it was odd that you did it in the explanation but not the example. Jun 29 '19 at 23:54
• @Neil Looks good. :) Jun 30 '19 at 16:34
• I'm wary of the use of the word "canonical" in this question, because it raises issues in my mind about normalisation of Unicode strings. I think that the intended challenge is really about byte arrays with constraints on the most significant bits, and I think it would be better to make that explicit (and to make the constraints explicit). Jul 2 '19 at 11:16
• @PeterTaylor There is that, but I wanted to exclude sequences such as E0 80 A0.
– Neil
Jul 2 '19 at 13:23
• @Neil, I think there's a miscommunication here. I'm saying that instead of talking about Unicode strings the question should explicitly state the FSS-UTF constraints on byte sequences, and maybe rule out encoding UTF-16 surrogate codepoints and codepoints greater than 0x10FFFF. Jul 2 '19 at 13:48
• @PeterTaylor OK but I really wanted this to be a string question rather than a byte sequence question...
– Neil
Jul 2 '19 at 16:20
• The problem then is dealing with the lexicographically first rearrangement of C3 A9 (é in normal form C) being 65 CC 81 (é in normal form D). Jul 2 '19 at 16:29
• @PeterTaylor Is that possible to do just by permuting the byte sequence?
– Neil
Jul 2 '19 at 16:34
• No, and that's why I'm arguing that the question should be phrased in terms of byte sequences rather than strings. Jul 2 '19 at 17:40
• There’s a mistake in the example: á is C3A1 and ¡ is C2A1. Good challenge. From the sound of it I/O will be flexible; this seems sensible since it keeps it open to more languages. Jul 2 '19 at 17:54
• @PeterTaylor I wanted it to be clear that these byte sequences must be a valid UTF-8 encoding of a Unicode string. I've tried rewriting the question a bit...
– Neil
Jul 2 '19 at 23:55
• Can you add some test cases? Jul 27 '19 at 14:35
• @MilkyWay90 Ok I added some
– Wheat Witch Mod
Jul 27 '19 at 14:47
• Okay, I give /support (also, you may want to add disallowing standard loopholes and using any default io method to finish it up) Jul 27 '19 at 14:48
• @MilkyWay90 Those are already standard I am not going to be making my post any more cluttered with stuff that adds nothing.
– Wheat Witch Mod
Jul 27 '19 at 14:53

# Move arrows along a contour

Posted here

• I've edited in a question since it needs 2D for clarity.
Jul 26 '19 at 8:48
• @Adám Only the arrows move. "+-|" always stay in place, or are "hidden" behind an arrow. So, you second example is correct (I deleted the first one) Jul 26 '19 at 9:02
• Continuing @Adám's question: Are shapes always separated by at least one space, or can they be next to each other like ++++\n++++, and we have to determine if it's a ++++\n++++ or +--+\n+--+ based on the directions the arrows are facing? I.e. is this a possible/valid input, and are those outputs correct? Jul 26 '19 at 11:26
• @GalenIvanov I didn't have anything but arrows move, and not it doesn't follow, because you couldn't tell what was behind the arrows, -s or +s which is what would make the two possible answers.
Jul 26 '19 at 11:28
• @KevinCruijssen Example 2 has two adjacent shapes with no (vertical) spacing.
Jul 26 '19 at 11:29
• @Adám Ah, you're right. As for your question however, you'd still know +<<+\n+>>+ is +--+\n+--+ due to the directions of the arrows in combination with the rule "when an arrow is on a corner, it keeps its current direction and changes it only after the turn is taken". See the pastebin in my previous comment for some test cases where you do know it's ++++\n++++ instead, because of the arrow directions. +^<+\n+>v+ will be two ++++\n++++ boxes, but +<<+\n+>>+ will be one +--+\n+--+ box. Jul 26 '19 at 11:37
• @KevinCruijssen Good point, but OP actually never says that the input is an obtainable state, though it does make sense. I still have a feeling that there could be ambiguous cases.
Jul 26 '19 at 11:41
• @KevinCruijssen The shapes will always be separated by at least one space, I'll add it to the description. Jul 26 '19 at 11:44
• @GalenIvanov Probably better indeed to not have to deal with confusing ambiguous cases. In that case I would also have at least a newline separation, so test case 2 should be slightly modified. :) Jul 26 '19 at 11:45
• @Adám Oh, I see - indeed I need to correct the second case to have a vertical space between the shapes. Jul 26 '19 at 11:51
• Even single tracks can be incredibly difficult: [" ++ ","++++","++^+"," ++ "] only has one possible output: [" ++ ","++++","+++>"," ++ "]
Jul 26 '19 at 11:55
• @AdámYes, this is the only output. Do you think a condition that sharp turns are forbidden will help? (this means no two + can be adjacent) Jul 26 '19 at 12:21
• @GalenIvanov Maybe that's indeed better to reduce confusion and make the challenge someone more manageable. Although you can still deduct the solution in Adam's comment above, having no spaces inside the space makes it rather difficult to parse correct. Always having at least one |/- between two + will always give the shapes always spaces, making it easier to parse individual shapes. In which case Adam's one would become [" +-+ "," | | ","+-+ +-+","| |","+-+ ^-+"," | | "," +-+ "] -> [" +-+ "," | | ","+-+ +-+","| |","+-+ +>+"," | | "," +-+ "] Jul 26 '19 at 13:55
• @KevinCruijssen Thanks, I added clarification. Jul 26 '19 at 14:09
• @GalenIvanov Maybe also change the one Adam edited in, since it's still with ++ below one-another. :) Jul 26 '19 at 15:08
• I found a lot of similar questions, but not quite the same. Would it be considered a duplicate? Aug 1 '19 at 8:17
• we've had double factorial closed before as a dupe of the vanilla factorial question Aug 1 '19 at 12:03
• @Giuseppe Thanks! I found that post, but I thought the variable factorial range might make it considerably different from the original challenge. Aug 1 '19 at 12:12
• Can we take input as two integers?
Aug 1 '19 at 12:49
• Can you give a definition for the multi-factorials above 2? Aug 2 '19 at 4:55
• @Adám That makes the challenge somewhat easier, but I suppose it is fair. I added the other input option. Aug 2 '19 at 7:04
• @MilkyWay90 Yes! Totally skipped that part, oops. Is it clear enough like this? Aug 2 '19 at 7:05
• @KevinCruijssen Input numbers can be in any format, of course. I thought this was included in the default I/O rules, buy I will specify this in the challenge. Aug 2 '19 at 12:39
• @KevinCruijssen In the input, at least one factorial sign is expected, i.e. a positive integer. I suppose the correct return value for a factorial number of zero would just be the base, but as the challenge is to calculate a factorial, this seems like an unreasonable restriction. The same goes for a factorial number lager than the base. If the factorial number is equal to the base, the base should be returned as per the generalized formula. I will add additional examples to clear this up. Thanks for the feedback! Aug 2 '19 at 12:39
• @KevinCruijssen The range(start,stop,step) function in Python 3 returns a generator with an initial value of start (or 0 if not specified) and a final value of stop-1. For example, the list representation of range(1,4) is [1,2,3]. If this list is sliced as [1,2,3][::-1], the returned list is [3,2,1], which can also be achieved with range(3,0,-1). When the slicing operator is applied to the generator directly, a new generator is returned which generates the sliced list instead. Does that answer your question? Also, range(420,0,-30) would be a cleaner approach in this case. Aug 2 '19 at 13:08
• @Jitse Ah ok, now it makes more sense. I indeed knew range(1,4) is [1,2,3]. And I also knew [::-1] reverses the order, since I see it used in answers every now and then. Seeing the range(1,4)[::-1] == range(3,0,-1) now I'm not sure why I didn't see it myself when I asked you the question. And yes, range(value,0,-n) would indeed be clearer than range(1,value+1)[::-n]. ;) Aug 2 '19 at 13:24
• Seems good except maybe you should specify that $n!^{(k)} = n\underbrace{!\ldots!}{k}$ (n!^{(k)} = n\underbrace{!\ldots!}{k}) Aug 2 '19 at 16:47

# Cliquish Program

Challenge: Write a program that accepts a character (or byte, see additional information) as input. Then:

1. If the character is contained within the source code, output a different character also in your source code.
2. If the character is not contained within the source code, output a different character also not in your source code.

This is a , so the shortest program (in bytes) wins.

• Your program must consist of at least 2 distinct characters.
• Your program must have at least 2 possible outputs.
• Your program does not have to be deterministic; it may output a character at random (with any distribution), so long as it conforms to the above criteria.
• Your program may optionally take a byte as input instead of characters. If you do, the code page the input is written in must contain at least each distinct byte in the source code, as well as at least two different bytes not in the source code.
• You may take input and give output in any reasonable way. For example, you may take input as a function parameter, a command-line argument, a line from STDIN, a triple-nested array containing a single character, etc. You could output via return value, STDOUT, exit code (if applicable), fax output, etc. The input and output formats must be consistent, however.
• Your output can only consist of the required character, optionally followed by one trailing newline. Prompt information (such as ans =) is exempt from this rule; such unpreventable output is acceptable.
• Slightly more interesting than most generalised quines. Have you checked quine for dupes? Aug 2 '19 at 7:32
• @PeterTaylor related related related. I couldn't find any exact dupes. Aug 2 '19 at 19:39
• What if your program contains all but one possible character? What encoding are the characters in? UTF-8? latin-1? ASCII? Aug 2 '19 at 20:18
• @Beefster Hopefully I've addressed your first question. As per your second, I believe we have a standard consensus on what a character is Aug 11 '19 at 18:13
• By induction the program must have 4 possible outputs. Inside/outside of the source × two included in each (if choose one, output the other). Btw I don't understand the title Aug 22 '19 at 7:05

# ASCII Maze Unrendering 3000

Posted

• Part of the wall for the current only test case seems a bit too narrow. Aug 28 '19 at 2:37
• I think this could be considered a special case of this challenge, with slight differences in the voxel style. Aug 29 '19 at 6:56
• @flawr You're right. As written, this is a duplicate. Do you know if the reverse has been done, taking the 3d version and returning the original? Aug 29 '19 at 17:52
• I don't think the reverse has been done, but I'm not sure this would make a good challenge. I'm still thinking about how one could make this. I mean the 2d version you propose would make it a bit simpler. Aug 29 '19 at 19:10
• Yes. The full 3d version would almost certainly be impossible, because most voxels would be completely blocked. Here, every block is visible, and a human can figure out where the walls are, so a computer should be able to do it too. Aug 29 '19 at 19:17
• @Night2 Indeed, didn't notice that point, I fixed the samples in the rules to include AA-000-AA Sep 20 '19 at 6:25
• Are the letters mandatory to be uppercased, or could we output in lowercase as well? Sep 20 '19 at 9:51
• @KevinCruijssen Yes, letters are mandatory to be uppercase, also I feel like you ask that because of a builtin somewhere :P Sep 20 '19 at 12:36
• Fine by me. I was mainly asking because it isn't a core-part of the challenge, and in some challenges lowercase/uppercase/mixed case is all allowed. But you're indeed right that lowercase would save a byte in my language of choice 05AB1E, where A is the lowercase alphabet builtin, and I'd need an additional u to uppercase it. ;p But since number plates are always uppercase, I can understand to keep the uppercase mandatory here as well. I had prepared a 24-byter, but will throw it away for now since I feel this can be done shorter.. Will try again later when it's posted to main. :) Sep 20 '19 at 12:41
• Another question, or more recommendation: allowed both 0-based and 1-based indexing for answers. I see your test cases are 0-based, but some languages use 1-based indexing instead. Sep 20 '19 at 12:44
• @KevinCruijssen Sure, no problem with 1-based indexing, going to fix the rules to add that. As I've never used such languages, I often forget about them Sep 20 '19 at 13:19
• I would say if the format irl has to be in uppercase then following that would be better. I've got myself an 85-byte JS answer that conforms to the irl format though. Sep 21 '19 at 1:06
• @ShieruAsakoto That's what I also advocate for, minus all the dumb real life rules that would just make it unfun to do. Anyway, going to post this Sep 23 '19 at 18:41

# Almost Illegal Strings

Posted.

• Does the challenge need to have the robber code output "Well done!"? What if they could just submit any code with the substring that runs?
– xnor
Oct 24 '20 at 10:24
• @xnor That's fair enough - I just struggle to define 'program that runs'. Would you consider zero exit code and no stderr output reasonable? Or are there some languages that output to stderr even in a valid program? Oct 24 '20 at 12:00
• I think this is too similar to the original "illegal strings" question which basically turned into a cops-and-robbers anyway Oct 24 '20 at 18:26
• @Sisyphus I was thinking you could just copy whatever condition Find an Illegal String uses. But it doesn't seem to be that rigorous, saying "The compiler/interpreter/runtime must give an error when given any source code that contains your string as a substring." I think requiring no output to STDERR is probably fine. Maybe though some languages give warnings to STDERR that golfers typically ignore? Note that defaults allow programs that print then crash, so just requiring output doesn't preclude a fatal error after.
– xnor
Oct 24 '20 at 21:12
• Rule suggestion: commenting out the almost illegal string is not allowed Oct 28 '20 at 15:33
• I think it's too thorny to define what comments are in a way that works across languages. One objective way to handle it would be to let cops specify a set of characters that are not in their code, where they might include their language's comment character(s) or quote literals.
– xnor
Oct 29 '20 at 0:40
• @xnor Ok, I've rewritten the challenge to just require that the program does not error, and feel the rules are fairly straightforward and watertight. Nov 1 '20 at 5:50
• @Beefster I considered this, and something like xnor's suggestion of banning characters. However, I think it ruins the purity of the challenge a bit, and for most languages it's very easy to avoid being in a comment (newline + end of comment block will do it). There are some languages which have 'inescapable comments', such as raw strings with specific delimiters, or something like Perl's __END__, but they're sacrifices I'm willing to make. Nov 1 '20 at 5:52
• The problem with not banning comments (or including things within strings, for that matter) is that it's quite easy to cop out and write a hello world with the almost illegal string appended in a comment. That takes out all the challenge. xnor's suggestion solves that mostly, but that does end up limiting cops a little bit to make the robbers' job an actual challenge. Nov 2 '20 at 16:25
• @Beefster Apologies, I have not been clear about my reasoning. My logic is that for the vast majority of languages, a cop can 'comment proof' their string trivially by adding a newline (to escape a single line comment) and an end of comment block (to end a multiline comment). For example, the string \nx"""x''' (with a literial newline) escapes all Python comments. You can do this in most languages - or am I missing something? Nov 3 '20 at 3:12
• @Beefster It looks like you were right - it is too hard without allowing Cops to ban characters. I'd like to apologise for not taking your feedback more seriously while the question was in the sandbox. Nov 6 '20 at 1:10

# Print random integers until 0

• Presumably, if the first number is zero, we just output zero and exit? Jan 16 at 18:57
• "integers may be separated by any non-digit, non-empty separator" can we output in zero-padded form (00 01 .. 98 99) so that a separator isn't necessary? What about codepoints/byte values (NULL - c)? Can it be a list-like object rather than a separated string? I think this would be better with more sequence-like IO rules Jan 16 at 18:59
• @pxeger Yes, if the first number is zero, you just output zero and exit. I don't think the standard is to output with zero-padding, so I'll say no on that. Byte values and list objects are both standard forms of outputting a bunch of numbers, so of course, those are allowed Jan 16 at 19:07
• Also, I assume it is not necessary that the program follows the indicated procedure (which would be unobservable anyway), as long as the output has the same statistical properties. So if a different procedure is used, perhaps the answer writer should justify it. (For example: generate a number K geometrically distributed with parameter 1/99, then output K nonzero numbers, then output a 0) Jan 16 at 19:07
• @LuisMendo Yeah, I'm pretty sure that "you don't have to follow the letter of the challenge so long as the behaviour is the same" is a standard rule, but in case not, I've edited in a sentence along with your example Jan 16 at 19:10
• I didn't fully define my example, sorry. You may want to change it to "then output K independent numbers with a uniform distribution on the set {1, 2, ..., 99}". That corresponds to the procedure you specify with a uniform distribution on {0, 1, ..., 99}. Jan 16 at 19:21
• @cairdCoinheringaahing are built-in functions for generating pseudo-random numbers forbidden? If not, is the challenge a very trivial one or am I missing something? Jan 27 at 23:17
• @Davide Trivial challenges are not necessarily bad, since it encourages participation in relatively hard-to-use or minimal esolangs. And I think this one is actually good because I smell many unexpected approaches to golf the problem. (Also, banning built-ins are considered bad.) Jan 28 at 0:26
• @Bubbler thank you so much for this train of information Jan 28 at 0:35
• @Davide Nope, all builtins are allowed. As Bubbler said, trivial challenges are only really bad if there’s no room for interesting solutions, which I don’t think is the case here Jan 28 at 10:06

# Remove Nth occurrences

• There is this but it got closed, Everything is clear, but can you replace, "the n" with "the integer n" in the last point of your assumptions list. For some reason that made me read the sentence multiple times. Feb 23 at 12:08
• Is there a reason for limiting the array values to 1-9? Feb 23 at 19:49
• @pxeger Because the values don't matter, so there's no reason to complicate it more. Plus, it can allow for some interesting string based approaches by taking $A$ as a single string Feb 23 at 19:52
• @pxeger It certainly helps that 0 cannot be part of the array, because then I can use it to erase values in APL. I'm sure other languages can take advantage of that too
– user
Feb 24 at 1:48

# To raise $$\ e \$$ to the power of a matrix code-golfmathmatrix

Posted

## Meta

• Is this clear enough?
• Is this a duplicate?
• Any other feedback?
• why not require exact calculation, it makes for a harder challenge but a more interesting one Apr 1 at 19:54
• @rak1507 it's irrational so an exact value can't be calculated Apr 1 at 19:55
• looked like there were methods on wikipedia but I could be wrong Apr 1 at 21:45
• Note that the exponential of a 9x9 matrix of 100's exceeds what floats can represent. You might want to lower the 100 bound or make allowances for that.
– xnor
Apr 2 at 6:30
• I think the precision convergence rule is too restrictive and too tied to that specific power series method, and some loose accuracy bound would allow more varied methods. For instance, one can approximate $e^M \approx (I+M/n)^n$ for large $n$.
– xnor
Apr 2 at 6:38
• @xnor I didn't read much into the matrix exponential (because I couldn't find the article on Wikipedia and was too busy watching the rest of the 3b1b video :P), so I hadn't not really realised there were other ways to compute it. What would you recommend? I still like the idea of requiring it to be observed to converge within floating point limits, because it adds an extra layer of challenge rather than just "repeat this step 100 times", but maybe that just isn't practical Apr 2 at 6:50
• I think convergence within floating point limits would unfortunately be hard and finicky here because of the nature of exponentials. The same way that $e^{100}$ and $e^{100.001}$ differ a lot, small errors in the computation can accumulate into huge ones. Also, the values in the output might be extremely small and become represented as zero. I'd have to think more about bounds, but maybe something like every entry within either 1% or 1e-4 of the true one should work.
– xnor
Apr 2 at 7:03
• My solution to floating-point errors is "the result should be within [insert error bound here] relative error for the given test cases". (The bolded part is VERY important. FP computation methods often have errors dependent on the magnitude of the input, so it is very hard to judge if an implementation is valid, even if the possible input range is specified. Explicitly giving the test cases makes it much easier to test submissions. Also, you need to craft the test cases carefully so that you don't accidentally ban a valid method or allow invalid methods.) Apr 4 at 23:28

# Non-quining infinite printer

Seems like the title could be better but I'm not sure what to do instead

I have heard that a monkey typing random keys on a typewriter, given infinite time, will eventually type out the entire works of Shakespeare, and in fact type out every possible string of characters of any length. This sounds to me like the basis for a profitable business venture in publishing. Unfortunately, however, as a result of previous failed business ventures, I am legally barred from possessing either monkeys or typewriters, so I'll instead need a program. I want this program to provably generate every possible string of characters, assuming infinite time and memory. Repetition is fine, as is overlap, as long as every possible string appears somewhere in the output. There's a catch, though. I imagine once my business gets off the ground and people realize the potential profits, they might want to get their hands on my program. The trouble is that since I'm outputting every possible string of text, in theory I'll eventually end up outputting the program itself, leaving it open to be stolen. To prevent this, I want the program never to output its own source code. It should still output every other possible string, just not itself (or, obviously, any strings which it is a substring of). Because my funds are currently very tight, I can't afford to pay for more bytes than are necessary, so I'm seeking the shortest possible program that does the job (This is a code-golf challenge, shortest answer in bytes wins). Is it communicated well enough what this challenge is asking for? Should I add a TL;DR and/or a more technical explanation of what's being looked for?

• I've had enough run-ins with the law in previous ventures, I'd like this one to go smoothly. So no abusing loopholes in the program, please.
• Given that this program is my financial plan for the next infinity years, I'd like some reassurance that it actually does what it's supposed to. Please provide at least a brief explanation of why your code works, since it can't exactly be tested.
• Any character encoding is fine, please specify though. The exception is that your source code must be printable in the encoding you use. Is this a reasonable way to handle this that is fair to all languages?
• No reading your own source, because that makes quine-related holes uncool, and uncoolness does not fit with my businesses' brand persona.
• How are the strings in the output separated? Some previous challenges about "print all possible strings" were closed as unclear because of this. Jun 7 at 1:06
• @Bubbler The strings don't have to be separated. What I mean is that every string should be a substring of the "main" output if that makes sense. Put another way, running a regex match on the output for any string of characters (other than the source) should return at least one result. Would adding something to that effect clear up that confusion? Jun 7 at 1:13
• It should still output every other possible string, just not itself (or, obviously, any strings which it is a substring of) Okay, the task makes sense now. I think you'll need to add that information somewhere before the sentence I quoted. Now I wonder if the task is actually possible... Jun 7 at 1:39
• @Bubbler Sure, it's possible. One approach is to store the program's source in a string, and then run some sort of code that generates every possible string, checking after each generation whether the generated string contains the source string, and only printing if it doesn't. There might be some trouble in making sure the source isn't present in a combination of two consecutively generated strings (i.e. if the source code is AB, then outputting XA and BX` consecutively is an issue), but a simple solution to that is to insert a character not present in the source between each pair. Jun 7 at 8:02
• Here's an implementation in Python tio.run/… Jun 7 at 8:03
• @jeje An easily thought solution is just use an unused char as split, but that likely be longer
– l4m2
Jul 1 at 16:40
• What do mean by "all possible strings"? Is this restricted to all strings consisting of printable ASCII? The entire Unicode table? Jul 8 at 1:14