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


To post to the sandbox, scroll to the bottom of this page and click "Answer This Question". Click "OK" when it asks if you really want to add another answer.

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.


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
  • Comments addressing specific points mentioned in the proposal
  • 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 requires more feedback, but it's been ignored, you can ask for feedback in The Nineteenth Byte. It's not only allowed, but highly recommended! Be patient and try not to nag people though, you might have to ask multiple times.

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.


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".

  • \$\begingroup\$ What if I posted on the sandbox a long time ago and get no response? \$\endgroup\$
    – None1
    Commented May 15 at 14:05
  • \$\begingroup\$ @None1 If you don't get feedback for a while you can ask in the nineteenth byte \$\endgroup\$
    – mousetail
    Commented May 29 at 13:27

4706 Answers 4706

55 56
58 59

Decimal to Troll

Discworld Trolls have a unique number system. From Wikipedia:

Trolls have a numeral system of their own, based on powers of 4.

The base numerals are one (1), two (2), three (3), many (4) and lots (16), which can be combined to form higher numbers.

When combined, each numeral's value is added to those of the others. Higher-valued numerals take priority over lower-valued ones, so that 4 is written "many" and not "two-two" or "three-one" and 20 is written "lots many" rather than "many many many many many". If there are no ones, twos or threes, the number is written with spaces between the numerals; if any exist a hyphen replaces the space between every numeral.

The Challenge

The challenge is to write a program that accepts a positive integer and outputs the equivalent troll counting string, including the correct separator (hyphen or space) based on the above rules.

Examples (including those from Wikipedia):

Input   Output
-----   ------
   1      one
   2      two
   3      three
   4      many
   5      many-one
  10      many-many-two
  20      lots many
  32      lots lots
 126      lots-lots-lots-lots-lots-lots-lots-many-many-many-two

This is code-golf, shortest answer wins.

  • \$\begingroup\$ Nice challenge! \$\endgroup\$
    – Leaky Nun
    Commented Apr 18, 2016 at 12:20
  • 1
    \$\begingroup\$ I feel like this is a dupe of this challenge about money. I think the greedy algorithm still works, the only differences that I see between these is the I/O formats and the amounts to use, which I'm afraid don't sufficiently differentiate them, in my opinion. \$\endgroup\$ Commented Apr 18, 2016 at 13:27
  • \$\begingroup\$ @FryAmTheEggman I can see the similarities, and yes, the repeating units in the output and separator are the main differences. But Discworld! :) Happy to withdraw it if consensus is it's too similar. \$\endgroup\$
    – Liesel
    Commented Apr 19, 2016 at 1:48

Tron Bot Racing

It's time to begin annual Tron Racing Tournament. Create a bot that will steer your cycle to a victory!


Board is a 100x100 square that wraps around its edges.


Bots leave impassable trail. In the beginning of the game, all the bots participating (2 in case of a duel) are placed randomly thorough the map. Then, at the beginning of each turn, all bots must decide the direction they will chose next (Up, Down, Right, Left) based (or not) on the available data, which is the empty cells in each of the directions. If bot tries to move into an occupied cell, his turn is repeated until it makes a valid move. If after 10 tries bot still won't make a valid move, it dies. Game ends when all bots die. Score is the length of your trail.


. . . . . d . .
. . . b b b b .     Received data:
. . . b . u b .     L0 U3 R3 D3 T1
. . . b . u b .     
. . . b . u b .     Length of line of sight is `ceil(map_size/2) - 1`
r . . b b B r r     and it wraps around map edges.  
. . . . . d . .     u, r, d - lines of sight
. . . . . d . .     B - bot, b - bot's trail 

If bot decides to go Left (and will collide with his own trail), he is invoked one more time with Tries increased: `L0 U3 R3 D3 T2'.


The engine is written in Node.js, so your bot should be a function in Javascript that accepts 1 argument (state array) and returns integer between 0 - 3 which corresponds to your chosen direction.

function RandomBot(state) {
  return Math.floor(Math.random() * 4);

0 - Left, 1 - Up, 2 - Right, 3 - Down

You can also write your bot in any other runnable language. It will be run every time a decision needs to be made, with data pushed into StdIn 3,3,0,2,1 and output (single integer) required at StdOut.

However, by using Javascript you have the advantage to use this to save data between runs.

Winner and conditions

Bots will be dueling with each other, each duel repeated 100 times. Standard loopholes apply.


How to create leaderboard? How to score wins and loses? Is there anything that can be improved? This is my first entry ever and I have already a working prototype. I have concerns with the data passed to bots. Maybe its too small? Anyway, let me know what do you think about it guys.

  • \$\begingroup\$ Similar \$\endgroup\$ Commented Apr 20, 2016 at 10:57
  • \$\begingroup\$ Even more similar. Except for limited data/sight, it's a duplicate. \$\endgroup\$
    – Geobits
    Commented Apr 20, 2016 at 13:56
  • \$\begingroup\$ I think that if the match would consist of bigger board and all the bots at once, it would be different enough to not be a duplicate. \$\endgroup\$
    – Are
    Commented Apr 20, 2016 at 15:03
  • \$\begingroup\$ I agree that a free-for-all should be sufficiently different, especially given the limited sight. Then again, with that many walls floating around, it could end up being very hard to avoid an impossible trap. You might want to do some test runs with some naive bots to see what happens. \$\endgroup\$
    – Geobits
    Commented Apr 21, 2016 at 2:29


Overview (basically the wiki page)

Chopsticks is a game played with two hands and two people. Both start with one finger out on each hand, the finger count. On a player's turn, they must choose one of their opponent's hands. That opponent adds the player's finger count to the one on that hand (and extends that many fingers). Once a hand's finger count has reached five or more, that hand's finger count is reduced to 0 and can't be used. Once both hands are out, the opponent wins.

To make the game more interesting, there is a mechanic called splitting: A player may use his turn to divide both his hand counts differently than he/she already has. A valid move would be to split from a 2 and a 3 to a 4 and a 1. An invalid move would be to split from a 2 and a 3 to a 3 and a 2. It is illegal to bring a hand back to life like a bunch of my friends like to do, as in split from a 4 and a 0 (a hand that is out) to a 2 and a 2 (back in). I deem it legal (since the Wikipedia article didn't say anything about it) to get one of your hands out using splitting, such as going from 3 and 4 to 2 and 5 (out).


Your task is to write a bot that will play chopsticks against another bot.


Every time your bot takes a turn, it will be given its opponent's finger count and its own finger count in this format:

[opponent hand 1] [opponent hand 2] [own hand 1] [own hand 2]

There will be spaces in between each value as shown above. Each value will be an integer. The bot should remember the hand numbers, as it is important to the output.


Your bot must take the data, decide what to do with it, and respond accordingly. Output is in this form:

[target hand] [attacking hand]

where [target] refers to the target opponent's hand and [hand] refers to the hand you are hitting the target with. A valid output would be 1, 2, which says that the bot wants to hit the opponent's first hand with its own second hand.

Problems and todo (sandbox)

  • I do not yet know how to make a program that handles all of this. I'll try to work on it.
  • There will be a bracket.
  • Should I make tweaks to the game to make it more suitable?
  • I may or may not follow through, but regardless I would like feedback.


  • 2
    \$\begingroup\$ If I understand correctly, this is an alternating turn game with about 6125 states. It's therefore very likely that every submission will play perfectly. \$\endgroup\$ Commented Apr 27, 2016 at 8:52

Visualize the Euclidean Algorithm by Tiling Rectangles

META: What's your opinion on moving this to a pop-con instead of a code-golf?

Suppose we have two positive integers, m and n. We can use Euclid's algorithm to calculate the greatest common divisor of these two numbers (the largest number that divides both numbers without a remainder). This is done by essentially taking successive subtractions of remainders until you reach zero. The linked Wikipedia article goes into much greater depth, and the mathematics behind it, for the curious.

Here, though, we're going to visualize the algorithm by taking a rectangle of size m x n and recursively tiling the rectangle with successively smaller and smaller squares until all space is consumed. The length of the side of the smallest square is thus the gcd(m,n).

Assuming m >= n, the first square is of size n x n, and is placed against the bottom edge. This repeats until a square does not fit, leaving a rectangle of size n x (m-kn) remaining, where k is how many n x n squares fit. That process then repeats on the newly-formed rectangle, starting on the left side, then the bottom, then the left, etc., until the original m x n rectangle is fully tiled.

Here's a beautifully done animated example, from that Wikipedia page, of 1071 and 462, showing the result to be 21.
By Proteins (Own work) CC BY-SA 3.0, via Wikimedia Commons.


  • Two distinct positive integers, m and n, via any convenient input method. Without loss of generality, you can assume m > n (for example, if you take input as a tuple, your program can assume that the first element is always the larger of the two, and you don't need to test size).
  • Your implementation should be able to handle input up to your language's default int size (or equivalent).


  • An image of at least 300px square, but no bigger than 1200px square, showing a rectangle of proportion m x n, tiled with successively smaller squares as described above. This means that for small inputs the rectangle will need to be stretched, and for large inputs the rectangle will need to be shrunk.
  • The image must be oriented so that m (the larger) is the vertical dimension and n is the horizontal.
  • Squares of the same size must be distinct. This could be done by coloring the squares differently from their neighbors, by enclosing each square in a border (as in the above animation), etc.
  • Output does not necessarily need to be in color, so long as the squares are distinct and understandable.
  • The image can be displayed on-screen or saved to a file.




You have an even number of identical balls. Half of them are "Light" balls and other half are "Heavy" balls which are heavier than the light balls for a unknown amount. You have to separate them into the "Light" box and a "Heavy" box using a scale instrument which tells you precisely for how much the left side is heavier than the right side when the balls are weighted on it.

Find a way to separate a given number of the balls with the minimal weightings as possible.

This is a challenge to programmatically reslove this question.

The solution should be an algorithm that would separate the given amount of balls with the least weightings as possible.

The Input can be any even number of balls, where the heavy balls will differ in weight from the light balls by a random amount. The balls are marked from 1 to n, and the "heavy" and "light" properties are assigned to all the balls randomly.

Now the program can take any number of balls and place it on the "right" side of a "scale" and then another amount of balls to be placed on the "left" side of the scale. It can read for how much exactly one side is heavier than the another, and then it can proceed to weight another set of balls until he can for sure tell for each numbered ball if it is "light" or "heavy". It should know how to process this in a least "weightings" or "uses of the scale" as possible.

So the goal is to write the most efficient program that can most efficiently separate the balls using the minimal amount of "weightings", and doing that for as many cases of given balls as possible.

  • 1
    \$\begingroup\$ This seems too simple. The optimal algorithm is well-known to the point where it's a common interview question. It would just be a race to be the first to implement it in the chosen language. \$\endgroup\$
    – user45941
    Commented Apr 29, 2016 at 19:17
  • \$\begingroup\$ @Mego Thank you for your review, Btw How would one write such an algorithm? Does something like that already exists? My main point of posting this was to answer that question, I would appriciate if you have any way of providing any help. \$\endgroup\$
    – Vepir
    Commented Apr 29, 2016 at 19:25
  • \$\begingroup\$ @Mego The "interview" question you're thinking of is probably a version with one different weight, as pointed out in the linked question. This seems challenging enough; one could even consider comparing different numbers of balls. \$\endgroup\$
    – feersum
    Commented Apr 29, 2016 at 20:45
  • 1
    \$\begingroup\$ What this needs to be a good question is some kind of output specification, e.g. giving the expected number of comparisons, an interactive protocol with the user giving comparison results, or some kind of tree decision representation. \$\endgroup\$
    – feersum
    Commented Apr 29, 2016 at 20:47
  • \$\begingroup\$ I would just set a pivot ball (e.g. the first one) and compare everything else with it. Runtime complexity O(n). \$\endgroup\$
    – Leaky Nun
    Commented Apr 30, 2016 at 14:36
  • \$\begingroup\$ @Kennylau but that is exactly the oposite of the solution. You would have then too many unecessary weightings, since the goal is to do it in least possible weightings no matter how complex the real solution might be \$\endgroup\$
    – Vepir
    Commented Apr 30, 2016 at 15:11

How Many Colours?

Take a grid of ASCII art rectangles as input and output the minimum number of colours you would need to colour it in so that no two rectangles of the same colour are touching.


  • Input can be any type of grid format (multine string, array of strings, etc...).
  • Rectangles only count as touching if the inside is adjacent to the inside of another rectangle (see the bottom-left rectangle in the example).
  • You may use different characters to # and space, but if you do, please specify what you use in your answer.
  • The grid itself will always be rectangular.
  • Grid width and height will always be between 3 and 99.
  • Shortest code in bytes wins.


The output for this input would be 3. An example arrangement of each colour 1 to 3 is labelled in the input below. Note how the bottom-left rectangle does not count as adjacent to the middle one.

# 1  #      # 1 #
######      #   #
# 2  #  3   #####
#    #      #   #
######      # 2 #
# 3  ########   #
#    #  1   #   #

Test Cases



Four Colour Theorem



Wheels on the Bus Go...


There is a bus heading for an intersection. Usually that is when buses would stop and give way to traffic, but there's a bomb on the bus! The bomb blows up if the speed of the bus falls below 50 miles-per-hour. Find out what speed the bus needs to travel at to avoid crashing into the cars going through the intersection.


  • Take a list of cars coming from the left and another list of cars coming from the right. The lists contain the distance of each car from the intersection as integers.
  • The distances will always be from 1 to 99 units.
  • There will always be 1 to 9 cars in either direction (2 to 18 total).


  • The speed the bus must travel to make it through the intersection without hitting a car.
  • The speed can be an integer from 5 and to 9 which is the speed in miles-per-hour / 10.


  • Each iteration, every vehicle moves speed in mph / 10 units forwards. The "path" of a vehicle for each iteration includes it's position before the iteration, it's position after the iteration and every position in between.
  • The cars always travel at 40 mph.
  • A crash occurs when the path of the bus intersects the path of a car in the intersection.
  • The bus starts 20 units before the intersection.
  • Cars cannot crash into other cars.
  • The speed of each bus cannot change during the simulation. You can only give each bus one speed.
  • Only solvable inputs will be given.
  • Shortest code in bytes wins.


TODO: Example doesn't make sense yet. Will complete later...

Here's an example using ASCII art to illustrate what would happen with this input and a bus speed of 6. Note: despite what it may look like, the intersection should behave as if it's size is only one unit.

  • B = Bus
  • . = Vehcile movement during iteration
  • C = Car

Input: [ ... ]

                  |     ^ |
                  |   | | |
------------------ ---     --------------
        <-                |    C . . . C
--  --  --  --  --         --  --  --  --
. C           C . |     .  . C     ->
------------------     --- --------------
                  |   |   |
                  |     B |
                  |   | . |
                  |     . |
                  |   | . |
                  |     . |
                  |   | . |
                  |     B |

Test Cases



  • \$\begingroup\$ So a bus can never crash with another bus with a different unit digit in the distance, if they are moving from different roads? \$\endgroup\$
    – Leaky Nun
    Commented May 1, 2016 at 15:16
  • \$\begingroup\$ @KennyLau There's only two roads, the sideways one and the up/down one. The only time buses from both roads will crash is if their paths overlap over the intersection. I'll try explaining it better when I edit it. \$\endgroup\$
    – user81655
    Commented May 1, 2016 at 15:19

From Smiles to Molecular formula!

SMILES is an algorithm to represent chemical molecules in one-line ASCII.

In this challenge, we will only be dealing with purely organic chemicals.

  • All the Hydrogens are not represented.
  • All single bonds not represented, double bond is =, triple bond is #. For example, ethane is CC, ethene is C=C, ethyne is C#C.
  • Branches are represented by (). For example, isobutane is CC(C)C, acetone is CC(=O)C.
  • Cycles are represented by numbers. For example, cyclohexane is C1CCCCC1.
  • All other things are ignored in this challenge.

Your task is to determine the molecular formula of a molecule, given its SMILES representation.


Any reasonable input/output format.

These are all accepted, for formaldehyde:

  • CH2O
  • C1H2O1
  • CxHxxOx (unary)
  • CHHO
  • OCHH
  • OHCH


This is . Shortest solution in bytes wins.


input       output
C=O         CH2O
O=C=O       CO2
C1C(=O)CC1  C4H6O
C#CCC       C4H6
  • \$\begingroup\$ I think you need to tighten up the specs. "Reasonable" is, of course, wide open to interpretation. For example, it's left unclear if the ordering in the output matters. Is it always carbon, hydrogen, oxygen, in that order (omitted if not present, naturally)? Is it "unreasonable" to say OCH2? \$\endgroup\$
    – dcsohl
    Commented May 2, 2016 at 13:20
  • \$\begingroup\$ @dcsohl Thanks, edited to allow that. \$\endgroup\$
    – Leaky Nun
    Commented May 2, 2016 at 13:28
  • \$\begingroup\$ Are you sure about your examples? My reading of the Wikipedia page is that cyclehexane's SMILES description should contain 6 Cs, but your example only has 5. \$\endgroup\$ Commented May 3, 2016 at 10:08
  • \$\begingroup\$ @PeterTaylor That was a typo, thanks. \$\endgroup\$
    – Leaky Nun
    Commented May 3, 2016 at 14:16
  • \$\begingroup\$ Which elements do answers need to be able to handle? \$\endgroup\$ Commented May 4, 2016 at 6:28
  • \$\begingroup\$ Also, can we assume that we won't be given aromatics so complicated that the cycle indication numbers go up to 10? \$\endgroup\$ Commented May 4, 2016 at 7:16

The incremental Gijswijt's sequence

The Gijswijt's sequence G is a sequence where the next term is the maximal number of repeating blocks of terms going so far backward.

The first numbers of this series are: 1, 1, 2, 1, 1, 2, 2, 2, 3

The incremental Gijswijt's sequence I is a sequence of Gijswijt's indices where any term of this last sequence I(n) has an image in Gijswijt G(I(n)) that is greater or equal all terms that precede it in that sequence G .

In other terms, It is an increasing sequence of indexes i for which G(i) is at least as large as G(j) for any j < i. Thus it contains the index of every 1 up to the first 2, every 2 up to the first 3, etc


  G= 1, 1, 2, 1, 1, 2, 2, 2, 3, 1, 1, 2, 1, 1, 2, 2, 2, 3, 2, 1, 1, 2, 1, 1, 2, 2, 2, 3, 1, 1, 2, 1, 1, 2, 2, 2, 3,...

  I= 1, 2, 3,       6, 7, 8, 9,                        18,                           28,                        37,...

Your program must output the most you can print from the starting of sequence until the delay between printing two consecutive terms exceeds 10 minutes, the actual number of outputs is your score.

For matter of reliability, the complete accurate "run-lengthed" G sequence must be linked through pastbin or any raw data repository.

the output will be so large to fit an int32 registry, so i suggest to print it modulo 1000007 or dont.

if the scores are not be divergent enough i will apply some salt, scoring is evaluated to N/T where T is executon time in seconds for the last term of sequence, the tie broken by the earlier post .

Only another 45 secs after the delay cap are given as an extra time.

  • \$\begingroup\$ I would VTC as unclear. \$\endgroup\$
    – Riker
    Commented May 4, 2016 at 16:08
  • \$\begingroup\$ hmmm what is unclear ? \$\endgroup\$
    – Abr001am
    Commented May 4, 2016 at 16:08
  • \$\begingroup\$ Winning criterion. until nothing appears in the console for 10 minutes is a bit vague. \$\endgroup\$
    – Riker
    Commented May 4, 2016 at 16:08
  • \$\begingroup\$ 10 minutes from last output, is this what u asked me to clarify ? \$\endgroup\$
    – Abr001am
    Commented May 4, 2016 at 16:10
  • \$\begingroup\$ "nothing appears" is a bit vague. I think you want something more like "the time to calculate the next term is > 10 minutes." \$\endgroup\$
    – Riker
    Commented May 4, 2016 at 16:11
  • \$\begingroup\$ yes when it exceeds that cap, execution must be halted \$\endgroup\$
    – Abr001am
    Commented May 4, 2016 at 16:12
  • \$\begingroup\$ .. I mean the wording in unclear. Can you say something like the time to calculate rather than the console is empty? \$\endgroup\$
    – Riker
    Commented May 4, 2016 at 16:15
  • \$\begingroup\$ if that makes you contented .... \$\endgroup\$
    – Abr001am
    Commented May 4, 2016 at 16:18
  • 1
    \$\begingroup\$ I found the definition rather hard to follow, and technically it defines an uncountable number of sequences. I suggest "The incremental Gijswijt's sequence is the (increasing) sequence of indexes i for which G(i) is at least as large as G(j) for any j < i. Thus it contains the index of every 1 up to the first 2, every 2 up to the first 3, etc. If you are familiar with the Records transform on integer sequences, this is effectively a Non-strict Records transform." \$\endgroup\$ Commented May 7, 2016 at 8:55
  • 1
    \$\begingroup\$ "For matter of reliability, the complete accurate "run-lengthed" G sequence must be linked through pastbin or any raw data repository." Why? If it's generated by the same process, it would have the same bugs. If it isn't, I don't see the point of asking every single answer to include a pastebin link. "i suggest to print it modulo 1000007 or dont." Either make this a requirement or don't. It complicates comparison of answers to make it optional. "Only another 45 secs after the delay cap are given as an extra time." Extra time for what? \$\endgroup\$ Commented May 7, 2016 at 8:59
  • \$\begingroup\$ @PeterTaylor 1. That is because it a contest for scores in increment, so any new record must be followed by a string of compressed numbers from the last terminus reached, until the new record using his own technique imagine the new score is 2 numbers far from the last result ? the algorithm must print a correct G series that is ground of I series. \$\endgroup\$
    – Abr001am
    Commented May 7, 2016 at 10:47
  • \$\begingroup\$ 2. The numbers could be too big and unintelligible, so either print a remainder or the difference of two edges or print it all along the console modulo something. \$\endgroup\$
    – Abr001am
    Commented May 7, 2016 at 10:49
  • \$\begingroup\$ 3. extra time for me to stop execution. \$\endgroup\$
    – Abr001am
    Commented May 7, 2016 at 10:49
  • \$\begingroup\$ a compressed string of numbers * in the first note \$\endgroup\$
    – Abr001am
    Commented May 7, 2016 at 11:31

Functional Programming in Your Language

A lot of modern programming languages allow some form of functional programming, but I don't often see them used. I'm curious to see how different languages tackle problems that are naturally solved with some form of functional programming. The winning entry to this contest will have the shortest total code as measured in bytes for these four questions

  1. Given a three-part list, return a list containing only those members for which the third element is a string.

    sampleIn1={{1,2,"fred"},{3,2,1.23},{3,2,"this one too",1.23},{},{"apple","banana",{1,2,3}}}

    sampleOut1={{1,2,"fred"},{3,2,"this one too",1.23}}

  2. Given a list of lists, each sub-list known to have exactly two elements, both of which are numbers, return a list of the first element in each sublist multiplied by the absolute value of the second.



In the sample output above I distinguish between integer and real output; in practice you can treat everything as a real number if you prefer.

  1. Given a list known to be composed only of numbers, return a list of the cube of each member, sorted by the square of each member (or its absolute value, which will have the same result).



  2. Given a list known to be composed only of numbers, return a list with each member of the list divided by the number before it. Since this is undefined for the first number in the input list, that element should be omitted. Where division by zero would result, the list should include notification of exception ("N/A" or something similar as befits your language of choice).



Presume that input has been assigned to a variable a in the natural list format for your language, assuming it has one.

To be clear, you don't have to use abstract functions or lambda calculus here, though I suspect that in many languages this will provide a short solution.

Standard rules apply, the examples above are only examples. Your code should work for arbitrary input.

  • \$\begingroup\$ This challenge explicitly disallows arbitrary classes of languages, is a do X without Y challenge, and a multi-part challenge with no interaction between the parts. The latter is not allowed on PPCG, and the others are highly discouraged. \$\endgroup\$
    – user45941
    Commented May 9, 2016 at 19:35
  • \$\begingroup\$ @Mego Read again, I explicitly allow any technique in any type of language. \$\endgroup\$ Commented May 9, 2016 at 19:36
  • \$\begingroup\$ I misread. This is still a multi-part challenge, which are not allowed. \$\endgroup\$
    – user45941
    Commented May 9, 2016 at 19:45
  • \$\begingroup\$ @Mego I can combine the challenges. Do you have any other objections or suggestions? \$\endgroup\$ Commented May 9, 2016 at 19:45
  • 1
    \$\begingroup\$ As far as I can tell, the challenges are combined. Anyways, the challenge feels like a random list of arbitrary, unrelated tasks. I think perhaps challenge #4 could stand on its own (especially if you made the operator a parameter). \$\endgroup\$ Commented May 9, 2016 at 20:07

Shortest path to the exit:

  • Given a n*n grid of 3 symbolic characters {'.','#',*} , where n is inputted, the dot is a safe spot to move from/to, # is a dragon who blows fire and spits magma, * is the outlet . Define (if it can be) the shortest path to take from the extreme upper/right to the star character that a moving point can take where:

    m is an integer m < n given by user-input or a function dimention with n, that generates obstacles # at the dynamic point m modulus n from the starting point, the last # point so far is replaced by an exit *, if no such path exists print 0 or a negative amount or undifined/null anything witch doesnt throw an error.


input: 7,3

why? the input generates this grid


The shortest path is marked as _


More TODO ...


  • Solution is cyclic

  • No solutions when m+1 divides n or n-1 . (to verify)

  • 1
    \$\begingroup\$ Like I said in your other challenge, please use proper English grammar and spelling. \$\endgroup\$
    – Nic
    Commented May 10, 2016 at 21:52
  • 1
    \$\begingroup\$ This looks like a standard path-finding, which we've already done. Making every mth place also make an obstacle doesn't make it sufficiently different IMO \$\endgroup\$ Commented May 10, 2016 at 21:52
  • \$\begingroup\$ @NathanMerrill how is so ? obstacles are systematically generated but not arbitrarily \$\endgroup\$
    – Abr001am
    Commented May 10, 2016 at 22:04
  • \$\begingroup\$ Hmmm...I guess that does allow for optimizations. Yeah, this would work for a code-golf. You should define what happens if there is no solution, or guarantee that there will always be a solution. \$\endgroup\$ Commented May 10, 2016 at 23:05
  • 1
    \$\begingroup\$ The text says that the start is the extreme upper/right, but the example seems to start from the upper left. Do you mean upper left? Also the slash makes it look like upper or right, rather than referring to a corner, which doesn't seem consistent with the example. \$\endgroup\$ Commented May 11, 2016 at 0:49
  • \$\begingroup\$ @trichoplax this is not really a big issue, up/right to down/left or up/left do down/right. \$\endgroup\$
    – Abr001am
    Commented May 11, 2016 at 6:47
  • \$\begingroup\$ @Agawa001 It's no issue either way - I'm just helping get it clear which one you want before the challenge goes live \$\endgroup\$ Commented May 11, 2016 at 14:30
  • \$\begingroup\$ @trichoplax the challenge will never get a soul to the other end anyways i m not really ready for another blizzard of downvotes \$\endgroup\$
    – Abr001am
    Commented May 11, 2016 at 14:40
  • \$\begingroup\$ I never know which challenges will make it to main. I just try to help clarify them until we can tell one way or the other \$\endgroup\$ Commented May 11, 2016 at 14:48
  • \$\begingroup\$ I dont know why serial dvter did miss to star the 4th comment, is it because is not castigating ! \$\endgroup\$
    – Abr001am
    Commented May 12, 2016 at 7:58
  • \$\begingroup\$ I think you have a gross misunderstanding of what constitutes serial downvoting. Serial downvoting is when somebody goes through and downvotes a lot of posts, typically out of spite. I downvoted both this and your other sandboxed post because they are very poorly specified, and you seem to have a tenuous grasp on the English language that makes understanding these challenges impossible. \$\endgroup\$
    – user45941
    Commented May 13, 2016 at 5:23
  • \$\begingroup\$ that's penguins being penguins \$\endgroup\$
    – Abr001am
    Commented May 13, 2016 at 7:46

Simulate a DNA Computer

DNA computers are very powerful computational models, theoretically able to solve NP-complete problems such as SAT deterministically in polynomial time. Your task in this challenge is to write a program/function that simulates the behaviour of a very simple DNA computer that accepts only four different kinds of commands.

DNA and Tubes

To make things a bit easier, we model DNA strands as non-empty words over {0,1}. So for our purpose, the following are all valid strands of DNA: 1, 010010, 01, 1100101.

Our DNA computer has access to an infinite number of (test) tubes T1,T2,T3,..., each of which contains a finite number of DNA strands. That is, Ti ⊂ {0,1}* for all i ∈ ℕ+. For example, T1 = {1,0100101,000} would be a valid tube. At the beginning of a simulation, all tubes are assumed to be empty (Ti = ∅ for all i ∈ ℕ+).


Our computer supports four different commands: Initialize (I), Merge (M), Filter (F), and Amplify (A). In the following, let the pairwise different numbers i, j, k ∈ ℕ+ denote indices of tubes Ti, Tj and Tk. Furthermore, let n ∈ ℕ+ and b ∈ {0,1}.


  • Description: We take all possible DNA strands of length n and put them into tube i.
  • Syntax: i = I n
  • Semantics: Ti ← {0,1}n
  • Example: After the execution of 2 = I 3, we have T2 = {000, 001, 010, 011, 100, 101, 110, 111}.


  • Description: We mix the contents of tubes j and k and put them into tube i.
  • Syntax: i = M j k
  • Semantics: Ti ← Tj ∪ Tk ; Tj ← ∅ ; Tk ← ∅
  • Example: If T2 = {00, 111} and T3 = {1, 010, 00}, then after the execution of 1 = M 2 3, we have T1 = {00, 111, 1, 010} and T2 = T3 = ∅.


  • Description: We remove all DNA strands from tube j whose n-th bit is not equal to b. We put the remaining strands into tube i.
  • Syntax: i = F j n b
  • Semantics: Ti ← Tj ∩ {0,1}n-1∘{b}∘{0,1}* ; Tj ← ∅
  • Example: If T2 = {1010000, 111, 1, 0101}, then after the execution of 1 = F 2 3 1, we have T1 = {1010000, 111} and T2 = ∅


  • Description: We put an exact copy of the contents of tube j into tube i.
  • Syntax: i = A j
  • Semantics: Ti ← Tj
  • Example: If T2 = {1010000, 111, 1, 0101}, then after the execution of 1 = A 2, we have both T1 = {1010000, 111, 1, 0101} and T2 = {1010000, 111, 1, 0101}.


Input will be a DNA program, i.e. a sequence of these four commands, that can be read from STDIN, taken as a function argument or even be stored in a file. It's up to you whether you take them as a list or a string with some kind of separator. Also, you can choose a different separator for the parameters of the commands or encode each command as a list as long as you do so consistently. For example, instead of the command 1 = F 5 10 0, you may use [1,"F",5,10,0], 1;F/5/10/0, 1=F(5,10,0) or the like. You may assume that the input is always syntactically correct. For example input/output pairs, see below.


You have to output a truthy value iff tube 1 is not empty (i.e. T1 ≠ ∅) after the execution of the DNA program specified in the input. Otherwise output a falsey value. Note that you are not actually required to simulate the DNA program step by step - if you find a more clever way to calculate the output of a given program, feel free to use it.


In the below examples, all commands are ;-separated and encoded as described in the "Commands" section.


  • 1 = I 20
  • 2 = I 4; 1 = A 2
  • 3 = I 1; 1 = M 3 9
  • 1 = I 4; 2 = A 1; 3 = F 1 1 0; 4 = F 3 2 0; 5 = F 2 1 1; 5 = M 3 4; 1 = M 2 5
  • 1 = I 3; 2 = A 1; 3 = A 1; 4 = A 1; 5 = F 2 1 1; 6 = F 3 2 0; 7 = F 4 3 1; 2 = M 6 7; 1 = M 2 5; 2 = A 1; 3 = A 1; 4 = F 2 1 0; 5 = F 3 2 1; 1 = M 4 5 (1)


  •  (the empty program)
  • 2 = I 5
  • 1 = I 2; 2 = A 1; 3 = F 1 2 0; 2 = A 3; 1 = F 2 2 1
  • 1 = I 1; 2 = I 1; 3 = M 1 2
  • 1 = M 2 3


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

1 In case you are interested: this example evaluates the formula (x1 ∨ ¬x2 ∨ x3) ∧ (¬x1 ∨ x2), that is, the contents of T1 after execution of the program are exactly the assignments to (x1,x2,x3) that make this formula true. One can create similar such programs for any 3SAT formula. The number of commands needed is linear in the size of the given formula.

  • 1
    \$\begingroup\$ I think this question would benefit from being written in a more layman-friendly and less symbolic way. While I might know that Ti ⊂ {0,1}* means that each test tube is a subset of the kleene star of the set {0, 1} I don't think every user of this site will. You also use things like ℕ+ instead of saying, say, "positive integers" and so on. This is just my personal opinion, but I think if you can explain something with words instead of symbols without compromising much in terms of length, you are more likely to be understood when using words. \$\endgroup\$ Commented May 11, 2016 at 18:47

Inspired by this, but also different. I need help phrasing things, putting them together coherently, etc.

Also, I can't decide on what the magic numbers (size, toggles per turn, etc.) should be.

Lastly, is this even winnable?

(oh, and if anyone wants to write a nice "backstory", that'd be much appreciated)

(also I have a couple of notes to myself in there so I remember what I was doing when I come back to this later)

Murderous Life


The game is played on a 100-cell-wide, 300-cell-long board. It's cylinder-shaped -- patterns will wrap around the long sides, but not the short ones. Attempts to toggle cells behind the short edges will fail, and all cells along the short edge are considered dead. The center 200x100 area (the "no man's land") is the focus of the game. The farthest left 50x100 area (next to the origin) is the Police Headquarters, and is where the police can send units from. The far right is the Robber Hideout, and is where they operate from.

Your program will communicate with the controller via standard input and output. Each message is terminated with a newline (\n, ASCII code 10). The code your program must exit when it receives Control+C (ASCII code 3). It doesn't have to stop immediately -- for example, if you have to close IO handles -- but it should take less than a second. It also doesn't have to end cleanly -- throwing an error is fine. As long as you've tidied up after yourself.

Immediately, both programs print to STDOUT their name and their author's name, with a hyphen in between, followed by a newline. This signals that they are ready to begin receiving input. After that, the turns will start immediately. The turns work like this:

  1. Both players are sent a string containing the current map through their STDIN. The format is detailed below.
  2. The desired moves are collected from each program in no particular order.
    • Note: If the moves are invalid for any reason -- they attempt to change a blocked square, too long, fail to precisely match the format, anything like that -- then the program is immediately ejected from the game, and I'll drop a comment on your post letting you know what happened.

  3. All of the moves are applied at once to the board
  4. One iteration of Conway's Game of Life (standard rules) is run on the map.
  5. The number of living cells in the No Man's Land is tallied.

The game runs for 5000 turns, after which the average number of living squares in the No Man's Land is calculated. This is the score of both the cop and the robber. Once three answers of each type have been submitted -- aside from the example ones -- I'll begin playing the answers against each other. The scoreboard will be updated daily until at least a week after the first answers have been submitted, or if it's later, three days after the last one has. The full score of any given program is the average of all of its scores.

Each program will be played against every other exactly once. Any attempts to communicate or disrupt the other AI -- except through the board -- are banned. If your bot doesn't respond to CTRL+D or CTRL+C, it will be banned.

Note that, if you have to do some cleanup before exiting, that's fine -- the "kill switches" don't have to work instantly. They do, however, have to work quickly. They can throw an error or something like that if you like.

You can always assume you'll get valid input.

In Cops version:

The point of the game, for the cops, is to keep the board as dead as possible. You can toggle up to 30 cells in the Police Headquarters per turn, creating or removing whatever patterns you like. At the end of the game, the Cop program with the lowest score wins.

In Robbers version:

The point of the game, for the robbers, is to make as many cells in the No Man's Land alive as possible. You can toggle up to 20 cells in the Robber Hideout per turn, in whatever arrangement you want. At the end of the game, the Robber program with the highest score wins.

[link to the opposite side's version]

Message format

Aside from the initial name string, all messages passed between programs will be like this:

1,4 12,0 9,125 299,6

Each pair is a coordinate pair, with the X values first and Y values second. The origin is at the top left of the board -- on the Police side of the board. The indexes are zero-based.

To be explicitly clear, the format is a space-delimited string of pairs. Each pair consists of two base-ten numbers, between 1 and 3 digits long, separated by a comma. The first number must not have a value greater than 299 or less than 0, and the second number must not have a value greater than 99 or less than 0. In addition, the first number must be between 0 and 49 (inclusive) if the player is a Cop, or between 250 and 299 (inclusive) if the player is a Robber.

I've written a basic example bot. To change what side it's on, simple change the comments on the lines indicated.

# Uncomment the part marked with the team this one should be on
place_at = (0..47).to_a.product (0..97).to_a
glider = [[1, 0], [2, 1], [0, 2], [1, 2], [2, 2]]
toggles = 30
place_at = (0..47).to_a.product (0..97).to_a
glider = [[1, 0], [0, 1], [2, 2], [1, 2], [0, 2]]
toggles = 20

puts 'GliderLover-QPaysTaxes'

while gets
  # We don't care what the board is like in this dumb AI.
  puts toggles.times.map {
    loc = place_at.sample
    glider.map { |offset| loc.zip(offset).map { |(a, b)| a+b }.join ',' }.join ' '
  }.join ' '

Is there anything else I need to specify?

  • \$\begingroup\$ .. I think this is the first C&R with a controller we've had? \$\endgroup\$
    – Riker
    Commented May 10, 2016 at 22:07
  • \$\begingroup\$ @EᴀsᴛᴇʀʟʏIʀᴋ Maybe! It fits CaR better than KOTH, though. \$\endgroup\$
    – Nic
    Commented May 10, 2016 at 22:08
  • \$\begingroup\$ @QPaysUnicornTaxes yeah. \$\endgroup\$
    – Riker
    Commented May 10, 2016 at 22:09
  • \$\begingroup\$ I think tagging this as KOTH is logical. The closest thing done before was: codegolf.stackexchange.com/q/51029/31203. Maybe putting both tags would be ideal. \$\endgroup\$
    – MegaTom
    Commented May 11, 2016 at 19:17
  • \$\begingroup\$ @MegaTom Hm, probably. It's certainly got elements of both. I still haven't finished the controller though, so until then I can't post anything :) \$\endgroup\$
    – Nic
    Commented May 11, 2016 at 19:38

An idea for a king-of-the-hill challenge:

You have a "memory arena" with a fixed size. You have several programs which "reside" in the memory arena (I mean you take the assembly and put it in the arena). The goal of the game is to get another program to access memory outside of this "arena" which then causes it to die because access outside of the memory arena is not defined. The last program standing wins.

You enter in assembly code (I have not determined which architecture yet). At the beginning of a round all of the entries get randomly placed in the memory arena. Each program will execute one instruction per turn.

It would be very similar to red code but in actual assembler.

Please feel free to post comments


Collatz or Hailstone sequence efficiently

Sorry for everywhere I posted in the wrong place and thank you to all of the mods for helping me find the sandbox.

Winner is the shortest run time to check whether all numbers up to N will end in x=1 or goes 70 iterations without returning to the original number or without decreasing under a step over Log(N) steps in a row under iterating f(x)=x/2 if x is even and f(x)=(3x+1)/2 if x is odd.

Hint: all one needs to show is that for all x under iteration it hits another y in the sequence that has already been shown to hit 1.

Sandbox questions

  • How can I phrase the above challenge. I set it with parameters that halt for all natural numbers n. I care more about the speed of the program then the shortness of the program.
  • \$\begingroup\$ Glad to see you've found the Sandbox now. I know it's somewhat counterintuitive that these are posted as answers instead of questions, but it keeps them all in once place with more chance the people who are looking to give feedback will find them. \$\endgroup\$ Commented May 18, 2016 at 6:36
  • \$\begingroup\$ For code that is judged by its speed, rather than its length, we have the fastest-code tag. I've added this and a few other tags. You can click on the tags to see other questions of the same type, and a description of the tag. Feel free to use different tags - I've just added some as suggestions. \$\endgroup\$ Commented May 18, 2016 at 6:48
  • \$\begingroup\$ I've removed the $s since currently this site does not support MathJax or LaTeX. Your challenge seems to work without it, but if you ever need mathematical notation I've found mathurl.com can be used as a workaround (it's fiddly so I'd only recommend it where the mathematical notation is essential). \$\endgroup\$ Commented May 18, 2016 at 6:52
  • \$\begingroup\$ I've looked at the challenges containing the word Collatz and it seems they are mostly code-golf (shortest code) challenges and there have been no fastest-code challenges so far, so I expect this challenge will not be a duplicate. \$\endgroup\$ Commented May 18, 2016 at 7:02
  • \$\begingroup\$ What form should the output take? Just true or false? Or the number of cases that don't get to 1 in 70 steps? I guess the latter will prevent all cases above a certain N having identical output. \$\endgroup\$ Commented May 18, 2016 at 7:30
  • \$\begingroup\$ The biggest problem I see with this challenge being fastest-code is that I don't see any real optimisation potential beyond the "hinted" memoization. Do you believe anything other than actually including memoization will affect runtime significantly? If not then this feels very much like a chameleon challenge for "write an efficient memoization function" and most of the answers will probably have unappreciably different time taken. \$\endgroup\$ Commented May 18, 2016 at 13:23
  • 1
    \$\begingroup\$ there are a lot of shortcuts to the clever person for instance if x is of the form 2^k then we're done, similarly if x of form 2^k-1 it will ascend k times in. row, so there are number theoretical optimization other then the hint stated \$\endgroup\$ Commented May 18, 2016 at 14:16
  • 1
    \$\begingroup\$ the output should be the numbers under n the fail conditions. i.e. n that doesn't hit one,doesn't cycle in 70 terms, doesn't run for more the Log (n)/Log (2). that is Log base 2 of N. \$\endgroup\$ Commented May 18, 2016 at 14:19
  • \$\begingroup\$ Just so you know, you are getting notifications because this is your post. Other people won't be notified unless you put an @ symbol before their name in your post, like @FryAmTheEggman. \$\endgroup\$ Commented May 18, 2016 at 14:49
  • \$\begingroup\$ oh thank you, @trichoplax I responded what inputs should be \$\endgroup\$ Commented May 18, 2016 at 14:56
  • \$\begingroup\$ Also note, neither of the optimisations you propose would actually improve the speed of a program that computes this. The Collatz operations are so trivial that calling them k times is faster than checking if a number is a natural power of 2. In addition, if you have memoisation you will only ever have to do each power of two once, rather than check each number for a non-trivial property. \$\endgroup\$ Commented May 18, 2016 at 14:57
  • \$\begingroup\$ @FryAmTheEggman Yes for those examples but this does not convince me that there are no shortcuts for the smart programmer hence the challanhe \$\endgroup\$ Commented May 18, 2016 at 15:00
  • 1
    \$\begingroup\$ This site isn't quite like other SE sites, I don't believe you should post a challenge if you yourself are not certain that there actually is challenge. That said, I'd guess the actual best approach is to grow a collatz tree upwards and just report the number of nodes that satisfy your properties, but that has the same problems of it being pretty much optimal already: I feel like the differences between responses would be largely negligible. Someone may prove me wrong, but until you know the competition will be worthwhile, I'd recommend against posting on the main site. \$\endgroup\$ Commented May 18, 2016 at 15:14
  • \$\begingroup\$ @FryAmTheEggman Are there other SE you would recommend I ask? \$\endgroup\$ Commented May 18, 2016 at 15:22
  • \$\begingroup\$ No this is the correct site for this question, I just don't think it would be particularly good. You have enough rep to chat by the way, it may be worth finding some other people's opinions; I am not the sole authority on the goodness of questions ;) \$\endgroup\$ Commented May 18, 2016 at 15:27

Kill the mosketeers

Taken a NxN square field, where you are supposed to be on the extreme upper right corner, n mosketeers are waiting an execution instruction that begins with the first lefttmost shooter alternatively until the last righttmost one, in a continuous unceasable order, meanwhile, between any shot and another you are allowed to move one step either to 4 allowed perpendicular directions.

T a period permitted to reload the riffle from a shot to another, dependently of steps taken from a move to another, a step is expressed in other words, as the time taken from two consecutive shots that of a mosketeer and his neighbor, so once T steps are elapsed, the mosketeer takes turn to shot again where two shots can occur in real-time.

Your task, is more than saving your head on your shoulders, but it is rather the ability of killing all the mosketeers while they are reloading their riffles by a knife, noted that : a mosketeer can shot in an horizontal dimention if his turn comes out, and no moketeer is between him and you, morover, a mosketeer do never move.

Given two inputs, N T, say in term of integer output how many mosketeers you are able to kill, return -1 or nil the case you end up killed no matter what you tried.





...*  |... .|.. ..|. |..| .|.. ..|. |..| .|.. ..|. ...| .... ....
....  |..* .|.. ..|. |..| .|.. ..|. |..| .|.. ..|. ...| .... ....
....  |... .|.* ..|* |.*| .|*. .*|. |*.| *|.. ..|. ...| .... ....
$$$$  |$$$ $|$$ $$|$ |$$| $|$$ $$|$ |$$| $|$$ *$$$ .*$| ..*$ ...*



example 2




...*  |... .|.. |.|. .|.| |... .|.| |... .|.| .... .|.| 
....  |..* .|.. |.|. .|.| |... .|.| |... .|.| .... .|.| 
....  |... .|.* |.|* .|*| |... .|*| |*.. *|.| .... *|.| 
$$$$  |$$$ $|$$ |$|$ $|$| |$*$ $$.$ $$.$ $$.$ *$.$ .$.$ 



  • 1
    \$\begingroup\$ 1) Do you mean musketeers? 2) I think the diagrams could do with a bit of explaining - it took me a while to decipher that | meant shooting, $ is a musketeer, * is you and the spaces separated different states. 3) It's not obvious to me why it's not possible to get all four musketeers in the second case, and also more test cases would be good (especially some that result in -1) \$\endgroup\$
    – Sp3000
    Commented May 22, 2016 at 5:08
  • \$\begingroup\$ @Sp3000 i m sorry to puzzle u this way beucause the challenge isnt about deceiphering patterns, but honestly i think that goes without saying, the second part where yu have been stuck deceiphering it, the two remaing shooters cannot be killed because either of both can shoot you horizontally when you are busy stabbing the other. \$\endgroup\$
    – Abr001am
    Commented May 22, 2016 at 9:22
  • \$\begingroup\$ any ways, you dont have to boggle yur mind more this will gonna be dead on meta, \$\endgroup\$
    – Abr001am
    Commented May 22, 2016 at 9:23

Scry sort

In Magic the Gathering, your library is a stack of cards, the effect Scry 2 causes you to take the top two cards of your library and arrange them as you choose on the top and/or bottom of your library.

enter image description here

You have six total choices:

  • Put both cards on top in either order
  • Put one cards on the bottom and one on top
  • Put both cards on the bottom in either order

If you are able to Scry 2 at will, you can repeatedly do so to arrange your library in any order. In this challenge, the cards of your library will be numbered from 1 to n, and your goal will be to arrange them in sorted order.

What should be the challenge here?

  • Code golf to find the minimum number of Scry 2's needed
  • Code golf to find any sequence that arranges your library, no matter how long
  • Fastest code or code challenge to sort in as few Scry 2's as possible.
  • \$\begingroup\$ I like the code challenge idea, but I think maybe it could be improved with Scry X instead of a constant 2. Given a nice range of cases to test, of course. \$\endgroup\$
    – Geobits
    Commented May 20, 2016 at 13:23
  • \$\begingroup\$ I think this depends a lot on whether there's an efficient algorithm or not. If there is, then code golf for optimal solution with a time limit might be good. Otherwise, code golf for optimal solution will just be plain BFS or something. Likewise, if there is an efficient algorithm, then fastest code might not be so good. As long as you don't know how easily this can be solved optimally, I'd probably go with code golf without requiring optimality. \$\endgroup\$ Commented May 20, 2016 at 14:12
  • \$\begingroup\$ Obviously in M:tG you don't generally know the order of your library, but it's not clear to me whether you're proposing that we would. \$\endgroup\$ Commented May 20, 2016 at 23:13
  • \$\begingroup\$ @PeterTaylor I was considering both for the code challenge. Finding out what cards are in your deck as you go and optimizing for expectation might be more interesting than trying to solve the whole configuration at once. \$\endgroup\$
    – xnor
    Commented May 21, 2016 at 6:13
  • \$\begingroup\$ Funnily enough I was just thinking of posting this as a challenge (as a fastest-algorithm) \$\endgroup\$
    – Blue
    Commented May 24, 2016 at 12:00

International Choice of Urinal Protocol efficiency

A long while ago, Randall Munroe of xkcd fame wrote a blog post entitled Urinal protocol vulnerability. The titular "International Choice of Urinal Protocol" is that when men enter a bathroom that has a row of urinals along the wall, they will first take the end urinals, and then take the urinals that are furthest from the other men. All men seek to avoid awkwardness, which happens when two men use adjacent urinals.

For example, if there are five urinals in a row, then by following this protocol, men will take urinals in this order:

1 3 2

In this case, the packing efficiency is optimal. However, when there are seven urinals, then this happens:

1  3  2

This is essentially the worst case. Fewer than half of the urinals are used, and Randall continues investigating when the best and worst cases happen. For this challenge, though, your only task is to calculate the packing efficiency of this protocol when given a number n of urinals, which is k/n where k is the number of urinals taken before awkwardness ensues.


  • Standard I/O and rules apply.
  • Input is a single positive integer n, which may be given as either decimal or unary.
  • Output must be either a float or a simplified fraction. If your language cannot do either of these easily (e.g. BF or Retina), then you may simply output k (in decimal or unary).

Test cases


 1 1.0
 2 0.5
 3 0.6666666666666666
 4 0.5
 5 0.6
 6 0.5
 7 0.42857142857142855
 8 0.5
 9 0.5555555555555556
10 0.5


 1 1/1 {or} 1
 2 1/2
 3 2/3
 4 1/2
 5 3/5
 6 1/2
 7 3/7
 8 1/2
 9 5/9
10 1/2

Urinals taken k

 1 1
 2 1
 3 2
 4 2
 5 3
 6 3
 7 3
 8 4
 9 5
10 5

Note: this is A166079.

Related: The Urinal Protocol, which asks for all the possible ways men could take urinals with no restriction on the first and no awkwardness.


Matching a string using a huge number of steps

Your task is to write a regex that matches a string you defined in as close to n steps as is humanly possible.

The regex must match the whole string without the global flag on.


The score would be regex length + string length + absolute difference between the number of steps and n.

For example, if n = 65536, this example has 6 bytes as regex, 49152 bytes in the string, and 65539 steps, which would account for a total score of 6+49152+3=49161.

Lowest score wins.


  1. n = 65536 (2**16)
  2. n = 59049 (3**10)
  3. n = 40320 (8!)

The total score will calculated from the scores of the three programs.


  • How can I make this challenge better?
  • \$\begingroup\$ Wouldn't the score be 6 + 49152 + 3 for your example? \$\endgroup\$
    – Sp3000
    Commented May 20, 2016 at 14:07
  • \$\begingroup\$ Yes, thank you for reminding. \$\endgroup\$
    – Leaky Nun
    Commented May 20, 2016 at 14:12
  • \$\begingroup\$ fyi if you don't end up allowing undershooting, the absolute difference... part should probably be (number of steps - 65536) \$\endgroup\$
    – Sp3000
    Commented May 20, 2016 at 14:45
  • \$\begingroup\$ Also, can we have a regex which theoretically gives a number of steps we can prove, but doesn't work in practice (e.g. due to insufficient memory)? \$\endgroup\$
    – Sp3000
    Commented May 20, 2016 at 14:46
  • 3
    \$\begingroup\$ What is a step? Whatever it is, it seems uninteresting as we can do an empty string with (){65536} or something like that. \$\endgroup\$
    – feersum
    Commented May 20, 2016 at 21:19

Find the smallest number bigger than the input whose digital sum is the input

"Digital sum" refers to the sum of all the digits in a number.

For example, the digital sum of 1324 is 10, because 1+3+2+4 = 10.

The challenge is to write a program/function to calculate the smallest number bigger than the input whose digital sum is the input.

Example with walkthrough

As an example, take the number 9 as the input:

9 = 1+8 -> 18
9 = 2+7 -> 27
9 = 3+6 -> 36
9 = 8+1 -> 81
9 = 9+0 -> 90

The valid output would be the smallest number above, which is 18.


Note that 9 is not the valid output for this example, because the reversed number must be greater than the original number.

Note that the input will be positive.


 2 => 11
 8 => 17
12 => 39
16 => 79
24 => 699
32 => 5999


This is OEIS A161561.

  • \$\begingroup\$ As far as I know it's either 2 or there is none \$\endgroup\$
    – user31373
    Commented May 23, 2016 at 14:14
  • \$\begingroup\$ I see what you mean, let me specify this a little better \$\endgroup\$
    – user31373
    Commented May 23, 2016 at 14:17
  • \$\begingroup\$ I edited the question to include the additional rule and changed the term digital root with digital sum \$\endgroup\$
    – user31373
    Commented May 23, 2016 at 14:38
  • \$\begingroup\$ Do you mean I should remove the mentioned part? \$\endgroup\$
    – user31373
    Commented May 23, 2016 at 14:44
  • \$\begingroup\$ Could I edit the question for you? You can rollback the edit afterwards if you don't like it. \$\endgroup\$
    – Leaky Nun
    Commented May 23, 2016 at 14:47
  • \$\begingroup\$ You are welcome to. This is my first Challenge I post here \$\endgroup\$
    – user31373
    Commented May 23, 2016 at 14:49
  • \$\begingroup\$ Done. How's it now? \$\endgroup\$
    – Leaky Nun
    Commented May 23, 2016 at 15:01
  • \$\begingroup\$ Also, you are welcome to join our chat. \$\endgroup\$
    – Leaky Nun
    Commented May 23, 2016 at 15:01
  • \$\begingroup\$ Yes thats exactly what I meant. thank you \$\endgroup\$
    – user31373
    Commented May 23, 2016 at 15:04
  • \$\begingroup\$ "because the reversed number must be greater than the original number." I don't know what you mean by this. Do you mean the output number must be greater than the input number? \$\endgroup\$ Commented May 23, 2016 at 16:39
  • \$\begingroup\$ Yes it has to be greater. If you look at the examples you can see it: input 9 and output has to be a number which has at least two numbers which have 9 as its sum. \$\endgroup\$
    – user31373
    Commented May 23, 2016 at 16:47
  • \$\begingroup\$ Can I post this abandoned proposal? \$\endgroup\$
    – user58826
    Commented Jun 9, 2017 at 13:03

Light the Way!

This is based on the Lights Out game. There is a grid of tiles, and clicking on a tile (performing a "move") toggles the state of the clicked tile as well as the (orthogonally) adjacent tiles. This variation will also toggle the diagonally adjacent tiles.

It is helpful to note that (on a board with only two states) all moves commute, so the order in which they are performed is not important. It follows that performing a collection of moves a second time will undo what was done the first time.

There are a few ways to present this challenge, so I'll describe some possibilities. Let me know what you think. The challenge could be one of the below:

  • Given a board size n (optional) and the initial state of the n-by-n board, determine an optimal collection of moves that will toggle every lit ("on") tile into its dark ("off") state.
  • Given n and a sequence of moves performed on an initially dark board of size n, provide the resulting matrix of states.
  • A variation on the above involving graphical output.

Input format would be flexible. n >= 1.

Snippet to show how the game works:

The board size may be adjusted in the first input field. The second field (functionality added by Conor O'Brien) will take a list of coordinates ([[0,0],[1,2],[3,0],...]) and perform the moves for you.

var table;
var color1 = "aqua",
	color2 = "yellow";
var moveList = [];

window.onload = function () {
	table = document.getElementById("lightGame");

	var updateButton = document.getElementById("updateButton");
	if (updateButton) {
		updateButton.onclick = buildTable;

	// added by Conor O'Brien
	document.getElementById("perform").addEventListener("click", function() {
		var toPerf = JSON.parse(document.getElementById("moves").value);
		function rec(arr) {
			var m = arr.shift();
			var x = m[0],
				y = m[1];
			var cell = table.rows[y].cells[x];
			if (arr.length) {
				setTimeout(rec, 500, arr);

function buildTable() {
	// get size
	var input = document.getElementById("size");
	var size = new Number(input && input.value || 5);
	var rows = size,
		cols = size;
	// clear moves
	moveList = [];
	moveHolder.innerHTML = "[]";
	// remove existing rows
	while (table.lastChild) {
	// create new rows
	for (var y = 0; y < rows; y++) {
		var row = document.createElement("tr");
		for (var x = 0; x < cols; x++) {
			var cell = document.createElement("td");
			cell.style.backgroundColor = color1;
			cell.x = x;
			cell.y = y;
			cell.onclick = function () {

function update(cell) {
	var x = cell.x;
	var y = cell.y;
	var xMax = table.rows[0].cells.length;
	var yMax = table.rows.length;
	// update cell
	// update orthogonally adjacent
	if (x > 0) changeColor(table.rows[y].cells[x - 1]);
	if (x + 1 < xMax) changeColor(table.rows[y].cells[x + 1]);
	if (y > 0) changeColor(table.rows[y - 1].cells[x]);
	if (y + 1 < yMax) changeColor(table.rows[y + 1].cells[x]);
	// update diagonally adjacent
	if (x > 0 && y > 0) changeColor(table.rows[y - 1].cells[x - 1]);
	if (x > 0 && y + 1 < yMax) changeColor(table.rows[y + 1].cells[x - 1]);
	if (x + 1 < xMax && y > 0) changeColor(table.rows[y - 1].cells[x + 1]);
	if (x + 1 < xMax && y + 1 < yMax) changeColor(table.rows[y + 1].cells[x + 1]);
	// update moves
	// added by Conor O'Brien
    moveList.push([x, y]);
    moveHolder.innerHTML = JSON.stringify(moveList);

function changeColor(cell) {
	cell.style.backgroundColor = cell.style.backgroundColor === color1 ? color2 : color1;

function getStyle(elt, styleProp) {
	if (elt.currentStyle)
		return elt.currentStyle[styleProp];
	return document.defaultView.getComputedStyle(elt, null)[styleProp];
body {
	background-color: darkslategray;
	color: white;
#gameDiv {
	text-align: center;
header {
	margin: 25px;
h2, h4 {
	color: red;
	text-shadow: -2px -2px black;

#lightGame {
	border: 1px solid white;
	margin: auto;
#lightGame td {
	/*background-color: aqua;*/
	padding: 1px;
	height: 25px;
	width: 25px;
#updateDiv {
	margin: 25px;
button {
	margin-left: 10px;

#autoMoveDiv {
	margin-top: 10px;

footer {
	position: fixed;
	bottom: 0px;
	width: 100%;
footer small {
	color: cyan;
	position: absolute;
	bottom: 0px;
img {
	float: right;
<div id="gameDiv">
		<h2>Light Game</h2>
		<table id="lightGame">
	<div id="updateDiv">
		<input id="size" name="size" type="number" min="1" max="20" pattern="\d{1,2}" value="5" required />
		<button id="updateButton" type="button">Update</button>
		Your moves: <span id="moveHolder">[]</span>
	<div id="autoMoveDiv">
		Auto move: 
		<input id="moves" />
		<button id="perform" type="button">Do Moves</button>

Related Questions

JsFiddle of the snippet I made.

  • 3
    \$\begingroup\$ Option 1 would be a duplicate IMO. I do like option 2, though. \$\endgroup\$ Commented May 24, 2016 at 17:36
  • 1
    \$\begingroup\$ I agree with Nathan Merrill. \$\endgroup\$ Commented May 24, 2016 at 17:37
  • \$\begingroup\$ @NathanMerrill This does include diagonals too, so it's different. But I don't know how different that'd be programmatically. \$\endgroup\$
    – mbomb007
    Commented May 24, 2016 at 17:40
  • 1
    \$\begingroup\$ Does the board wrap? \$\endgroup\$ Commented May 24, 2016 at 17:43
  • \$\begingroup\$ Option two sounds like it's pretty much a duplicate of this one, though. Except for the initial board state and diagonals, that is. \$\endgroup\$
    – Geobits
    Commented May 24, 2016 at 17:44
  • \$\begingroup\$ Does it need further variation? Hexagonal board? 3d? Broader effect? Random effect? Context dependent effect? \$\endgroup\$ Commented May 24, 2016 at 17:48
  • \$\begingroup\$ I'd definitely make diagonals bold. I completely missed that when reading. I think diagonals make either 1 or 2 unique. \$\endgroup\$ Commented May 24, 2016 at 17:50
  • \$\begingroup\$ @trichoplax The board does not wrap. \$\endgroup\$
    – mbomb007
    Commented May 24, 2016 at 20:01
  • \$\begingroup\$ "Given a board size n (optional) and the initial state of the n-by-n board, determine an optimal collection of moves that will toggle every lit ('on') tile into its dark ('off') state." Or you can have "determine an optimal collection of moves that will toggle every lit tile into its dark state and vice versa". \$\endgroup\$
    – msh210
    Commented Jun 15, 2016 at 22:53
  • 1
    \$\begingroup\$ @msh210 If the goal is to toggle every tile, the solution is trivial. If the goal is merely to end with all light, then with all dark, getting from one to the other is also trivial (it's the set of all moves minus the set from the first answer). \$\endgroup\$
    – mbomb007
    Commented Jun 16, 2016 at 13:25

Version Comparator

Given two version strings, return a positive, negative or zero value depending on which one is earlier. Version strings consist of one or more non-negative integers separated by full stops, optionally suffixed by a lowercase letter and a final non-negative integer. Examples of versions:

2.20 or 2.20.0 (these should compare equal)

When comparing versions the integers should of course be compared numerically, not lexically. Missing components should compare as zero against numbers, but they compare after letters. You should then be able to recognise that the above versions are in version order, but you can choose whether this should be a positive or negative result. Reversing the parameters should obviously negate the sign of the result, but you can return a different absolute value if you prefer.

Builtins that compare versions are disallowed, but things like regexes are OK.

This is , so the shortest program or function wins.

  • 2
    \$\begingroup\$ How do letters compare numerically? \$\endgroup\$
    – Leaky Nun
    Commented Jun 2, 2016 at 12:40
  • \$\begingroup\$ It should never be necessary. \$\endgroup\$
    – Neil
    Commented Jun 2, 2016 at 13:10
  • \$\begingroup\$ Test-cases please. Especially 1a1 vs 1a vs 1. \$\endgroup\$
    – Leaky Nun
    Commented Jun 2, 2016 at 13:52
  • \$\begingroup\$ @LeakyNun Added some more examples. 1a should compare as if it was 1a0 so less than 1a1 which is less than 1. \$\endgroup\$
    – Neil
    Commented Jun 2, 2016 at 15:49
  • \$\begingroup\$ How do 1a and 1b compare? \$\endgroup\$
    – Leaky Nun
    Commented Jun 2, 2016 at 15:56
  • \$\begingroup\$ @LeakyNun Well, you already know that 1.5a2 compares before 1.5b1... \$\endgroup\$
    – Neil
    Commented Jun 2, 2016 at 16:16

Find the duration of a worst-case brute-force attack

Given the following information about a 7-bit ASCII-encoded password and the computer that will crack it with a brute-force attack:

  • Length of the password in characters
  • Charset size (i.e total count of the possible characters one character in the password can be)
  • Number of passwords the computer can test in one second millisecond (rounded down)

Write the shortest program that finds out how long the attack will take in the worst-case scenario where the computer tries all possible passwords.

  • The output is the duration in this format: years months days hours minutes seconds milliseconds
    • One "month" is 30 days long.
    • Fractions of milliseconds are rounded up.
    • You can assume that the cracking finishes immediately if it takes less than 50 milliseconds, and make the program print out Instant in such cases.
    • Similarly, the cracking can be considered Neverending if it takes more than 292 billion years.
  • The program can output using any method, from merely printing to STDOUT to causing a kernel panic/bluescreen with the duration as the error message.
  • The input method to get the info about the password/the machine can be anything, as well. Don't use standard loopholes though.
  • It's not enforced, but strongly encouraged to write a standalone program.

Here's how to calculate the charset size:

  • Start with 0.
  • If there's a digit (in the password), add 10.
  • If there's a lowercase letter, add 26.
  • If there's an uppercase letter, add another 26.
  • If there's punctuation, add 32 (7-bit ASCII has this many punctuation characters).
  • If there's a whitespace character, add 2. Whitespace characters are horizontal tab (0x09) and space (0x20).
  • Any other character counts as non-printable (including backspace (0x08), DEL (0x7F), line feed (0x0A) and carriage return (0x0D)). Add 29 if there's any of them.

Count of all possible passwords is (charset size)password length.

Here are some applicable-in-real-life cases you can test your program with (let's assume the computer that will crack them can test 1 billion passwords per second, which equals to 1,000,000 passwords/millisecond):

  • 4 characters, charset size 10 (PIN) - 10,000 passwords, output is 0 0 0 0 0 0 1 or Instant
  • 8 characters, charset size 94 (at least one uppercase letter, one lowercase letter, one digit and one punctuation) - 6,095,689,385,410,816 passwords, output is 0 2 10 13 14 49 386
  • 10 characters, charset size 2 (weakest valid Discourse password, contains whitespace only) - 1024 passwords, output is 0 0 0 0 0 0 1 or Instant
  • 25 characters, charset size 26 (correcthorsebatterystaple) - 236,773,830,007,967,588,876,795,164,938,469,376 passwords, output is 7612327353651221350 2 14 0 26 4 939 or Neverending
  • 127 characters, charset size 96 (strongest password on newer Windows releases) - written below
  • 1024 characters, charset size 36 (4096-bit PGP key represented as a hexadecimal number) - written below

These are the stats of the maximum-strength Windows password:

Passwords: 560,333,510,486,846,899,384,847,242,571,130,277,659,458,884,466,874,695,582,912,274,460,529,559,443,783,341,570,989,525,270,653,136,186,432,110,439,597,936,820,880,106,519,625,601,191,574,799,863,912,148,304,962,133,852,037,202,160,056,511,510,962,873,278,300,126,526,144,267,006,137,180,032,492,751,016,171,207,701,495,935,943,049,216
Output: 18014837657113133339276210216407223432981574217685014647084370963880194169360318337544673523362047845500003550655797865897637169483847774934889398916928636347805229296463546812516445182705545212838429981490065783731353925307067135133992 5 15 19 58 55 944
Alternate output: Neverending

And these are the stats of the PGP key:

Passwords: 4,505,684,579,918,576,285,346,738,866,335,056,898,110,301,685,668,199,078,230,938,179,212,682,315,156,231,410,185,391,761,603,272,976,014,035,539,665,517,248,679,228,261,440,294,129,198,036,262,705,242,310,399,830,546,082,361,923,420,737,260,766,677,891,361,176,003,624,143,368,380,527,062,643,297,677,246,518,686,688,642,023,537,863,317,793,178,302,508,440,097,154,593,959,832,175,055,427,351,149,410,096,495,695,380,712,810,868,774,475,142,767,054,868,274,802,269,522,299,482,066,464,842,097,715,922,988,138,315,118,067,288,670,934,735,264,524,936,706,249,961,394,413,647,964,221,767,703,673,264,468,419,121,528,644,906,680,808,060,759,817,669,970,046,776,525,266,199,099,671,937,918,801,013,826,958,891,378,841,908,663,991,372,649,027,188,879,525,186,690,599,345,723,173,064,252,017,258,129,131,786,488,462,307,158,861,824,049,980,863,991,149,295,162,169,512,952,373,415,599,734,988,691,348,925,488,351,712,593,858,837,027,205,238,618,188,975,201,320,681,214,515,875,812,195,250,605,867,622,987,451,763,883,339,709,733,502,125,838,221,788,546,339,051,347,360,900,518,381,976,167,289,930,943,228,024,924,785,158,428,496,314,937,921,503,359,298,542,415,845,218,449,360,806,235,379,253,546,728,753,218,950,843,742,471,105,739,555,344,908,900,309,982,913,223,331,321,839,212,821,903,239,320,600,564,890,951,140,667,647,680,682,245,252,370,183,758,578,065,733,075,207,856,432,661,797,090,351,101,165,469,273,829,754,476,555,209,675,613,232,875,323,406,611,257,057,059,099,019,633,298,079,410,970,345,108,939,943,042,100,267,260,413,671,556,828,411,902,575,269,208,445,279,433,655,878,082,023,068,697,154,581,711,817,787,688,949,105,583,339,471,599,190,831,084,304,744,483,799,555,478,063,729,574,297,623,870,804,763,558,027,580,772,927,971,329,879,231,979,556,301,616,929,595,576,646,883,067,201,999,872,899,862,889,211,861,332,535,050,455,387,251,034,043,732,447,006,164,551,883,918,733,705,027,099,846,583,024,013,092,062,384,703,436,459,115,108,358,829,136,251,317,699,709,899,140,949,893,425,335,769,021,022,912,434,045,643,544,474,460,899,799,213,759,568,795,794,758,914,390,056,283,305,470,380,859,003,818,724,678,434,816
Output: 144858686339974803412639495445442930108998896787172038266169565946909796654971431654622934722327449074525319562291578211137739886840732034401886018044055761311424449664413690224320369299057721231224396352345948448015131278860508182828147139982752631922511354755096078964028889980704480936709984283352948061204198196785328857204061945957268141550998891534834171375541476907019128991072373909056348731183618329634024763694746476776233417623704464804027405450152026906721990999895827471385353870130056140660354679074035526421905828555132520211676677361401337091034117370453939870215183392876069255694823382473711006907851853458746913295694931911314073828877816349504523255816791677974298928074750103049081088894521647398444396729546431174466495229648516324713327536964168664025148591452750098101445502202880078966283755495859954505040675103796820824907455740718188735077328268047865426806174561044520100917915500979652319301547868727504821981520811835192875926630119576922600465887060849654310721522802609638109522185755307201898676461606130734024600227278608209698963323356340446015796148617903068964091403666193996894642822309315198786075754477250953946657292049336910661279747924178751224344877465829301109562043071275369906871767991229129085786546569052197642684662087651029574035646976531236521763373563846425925268656816387911380422031991615290633773786744123323731112880994579065426763237282889858685438654794679302568796507941872848896038602862540480809810919146613018187362072374644736799940064590439265446053422181856817801562474722208358918298576208528044087753034364036 10 24 22 32 4 679
Alternate output: Neverending

  • \$\begingroup\$ Is there any wrong information? \$\endgroup\$
    – SE is dead
    Commented Jun 4, 2016 at 20:43
  • \$\begingroup\$ Please provide proper test cases, i.e. with all input parameters (speed of computer is missing) and solutions, so that we can verify our programs. \$\endgroup\$
    – nimi
    Commented Jun 4, 2016 at 22:36
  • 2
    \$\begingroup\$ Unless there's a good reason you should should go with our defaults and allow functions and programs . Don't allow loopholes. \$\endgroup\$
    – nimi
    Commented Jun 4, 2016 at 22:42
  • 2
    \$\begingroup\$ IMO this challenge would be better if it allowed simply returning/outputting an integer number of milliseconds. As it is, the mixed-base conversion will be trivial for languages that have a builtin for it, and nearly as long as the code to compute the length of time (if not longer) for languages that don't. \$\endgroup\$
    – user45941
    Commented Jun 6, 2016 at 8:51
  • \$\begingroup\$ You can see how many people agree with Mego's suggestion in the discussion on meta. \$\endgroup\$ Commented Jun 6, 2016 at 13:40
  • 2
    \$\begingroup\$ In response to "It's not enforced, but strongly encouraged to write a standalone program.": Elsewhere in the same discussion it recommends avoiding saying "ideally your code will.... That will just be ignored anyway (otherwise the code won't be competitive). Make a definite decision one way or the other rather than a recommendation. \$\endgroup\$ Commented Jun 6, 2016 at 13:46

Array of Integers to Array of Digits

Given an array of arbitrary length containing only integers, output an array of integers of each digit of each integer in the array.


  • The input array will only consist of integers in base 10

  • The integers will be in the range of [0, MAX_INT] where MAX_INT is the greatest value an integer can have in your language

  • Assume that all integers will be positive, however you can interpret the integers as signed or unsigned

  • String manipulation and the use of any regex is banned by default

  • The outputted array must be exactly 1 deep and contain only integers

  • The order of the digits in the outputted array must be exactly as they were in the inputted array

  • Leading zeros are to be stripped, as they should be when parsed as an integer


[2, 3, 5, 7, 11, 13] -> [2, 3, 5, 7, 1, 1, 1, 3]
[1, 2, 3, 4, 5] -> [1, 2, 3, 4, 5]
[123, 456, 789, 101112] -> [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 0, 1, 1, 1, 2]
[0, 000, 000123] -> [0, 0, 1, 2, 3] //'000' is treated as '0' and '000123' is treated as '123'
  • 1
    \$\begingroup\$ Seems pretty straightforward, but pretty trivial in most languages. (Trivial does not mean off topic, but you will likely get lots of answers, as well as some downvotes). You should specify that the integers are in base 10. \$\endgroup\$ Commented May 25, 2016 at 14:19
  • 1
    \$\begingroup\$ Will the input array contain 0 or negative integers? \$\endgroup\$
    – Leaky Nun
    Commented May 25, 2016 at 19:30
  • 1
    \$\begingroup\$ You say integers, but I take it you mean positive integers? \$\endgroup\$
    – xnor
    Commented May 25, 2016 at 22:19
  • \$\begingroup\$ I updated the specification \$\endgroup\$
    – MrPublic
    Commented May 26, 2016 at 12:22
  • \$\begingroup\$ You should clarify that leading zeros are stripped, so that people don't need to infer that from the last test case. \$\endgroup\$ Commented May 26, 2016 at 18:51
  • \$\begingroup\$ What leading zeroes? Numbers can't have them if they are not strings. Is it an array of numbers or array of strings? \$\endgroup\$
    – Qwertiy
    Commented May 29, 2016 at 23:12
  • \$\begingroup\$ It may be interesting to ban the use of string manipulation. This would change the challenge a lot, but it will force the answers to be less trivial. (also note that such a challenge may be frowned upon: meta.codegolf.stackexchange.com/a/8079/31203) \$\endgroup\$
    – MegaTom
    Commented Jun 1, 2016 at 15:19
  • \$\begingroup\$ You mention signed integers, but none of your examples contain negative numbers. Do we only need to support non-negative numbers? If not you should specify how negative numbers should be handled and add an example to the test cases. \$\endgroup\$ Commented Jun 3, 2016 at 11:33
  • \$\begingroup\$ Personally, I doubt that string manipulation is the easiest way to do this in most languages? I don't think banning it improves the question. It just seems to make a bunch of languages unusuable, and the rest just entirely ignore it? \$\endgroup\$ Commented Jun 9, 2016 at 20:08

Ping Pong

The Challenge

This challenge is to make a program that prints a text ping-pong animation. Your program is to display a string of tildes with a PING on it moving to the right. Each tick, the text PING moves one to the right one character, reducing the number of tildes on the right by one and increasing the amount on the left by one. Once the PING reaches the right side of the string, it changes to a PONG and the reverse happens (i.e it moves to the left instead).


  • The number of tildes must always be the same
  • The number of tildes must be at least 30
  • The number of milliseconds between ticks must be at least 10 ms and at most 1 s
  • The PING must start at the left hand of the string


Your score is the number of bytes plus/minus the following (all that apply):

  • -10 bytes for browser implementation using the ping after the hash Example
  • +10 bytes if your implementation does not clear previously outputted frames
  • More suggestions welcome

Lowest score wins.

Example Implementation (JS, Ungolfed)

i=0;b=false;len=50;td=40;function urlPong(){location.hash=new Array(i+1).join("~")+(!b?"PING":"PONG")+new Array(len-4-i+1).join("~");if(!b){if(len-4-i<=0){b=true;}else{i++;}}else{if(i<=0){b=false;}else{i--;};}setTimeout(urlPong,td);}urlPong();
  • 1
    \$\begingroup\$ Why do you restrict this to be in a browser? That seems to add an unnecessary limitation on which languages can reasonably participate. \$\endgroup\$ Commented Jun 9, 2016 at 13:06
  • \$\begingroup\$ Okay, I made it less browser dependant \$\endgroup\$
    – takra
    Commented Jun 10, 2016 at 0:57

Implement this cipher

(I'm not sure what to call this cipher)


Use the algorithm (explained in the Algorithm section) to implement a certain cipher.

The program must read input from STDIN or the closest available equivalent, use the algorithm to generate the ciphertext and a key.

The ciphertext and the key will be written to STDOUT or the closest available equivalent, preferably with the format (ciphertext)\n(key).


Convert the characters in the string into the respective ASCII values. For example:

Hello -> 72 101 108 108 111

Next, you will need to generate a key as long as the string with random numbers in the range of 0-9.

Hello -> 62841

Add the integers in the random number sequence to the ASCII values of the string. In the above examples, 72 would become 78, and 101 would become 104.

72 + 6 = 78, 101 + 2 = 104, 108 + 8 = 116, etc

Next, convert the new ASCII values back to characters. In the above examples, the text Hello has become Nhttp.


(These are simply examples of what the output might look like. The output can and will vary.)

Hello, World!


This will be encoded
Zhjs$~koo gj$iuhofgj


  • Submissions must be full programs.
  • Languages newer than the challenge are allowed.
  • Submissions will be scored in bytes.
  • Standard loopholes are forbidden.
  • This is code-golf, so the shortest code wins.

I'm sure this challenge needs a little tidying up and making it look and sound a bit nicer. I'm not very good at writing challenges, so I'd like some advice.

  • \$\begingroup\$ This is an actual cipher (though not usually with ASCII codes). I don't remember the name right now. But seeing that, it might be a dupe. \$\endgroup\$
    – Riker
    Commented Jun 12, 2016 at 15:13
  • \$\begingroup\$ @EᴀsᴛᴇʀʟʏIʀᴋ Oh, I didn't know that. I thought it was original. \$\endgroup\$
    – m654
    Commented Jun 12, 2016 at 15:32
  • \$\begingroup\$ Yeah, it's called something like a key cipher. \$\endgroup\$
    – Riker
    Commented Jun 12, 2016 at 15:34
  • \$\begingroup\$ @EᴀsᴛᴇʀʟʏIʀᴋ What do you think of this challenge? Do you have any advice for making it... better? \$\endgroup\$
    – m654
    Commented Jun 12, 2016 at 16:16
  • \$\begingroup\$ If properly implemented (i.e. with a pre-shared key which covers the full range of symbols rather than just 0-9) this would be a one-time pad, which is (in some sense) the limit case of the Vigenère cipher. It's not quite a dupe of the Caesar cipher question, but it's barely more complicated. \$\endgroup\$ Commented Jun 12, 2016 at 21:57
  • \$\begingroup\$ @PeterTaylor The Caesar cipher shifts the characters up the alphabet, but this one shifts the up the whole character range. \$\endgroup\$
    – m654
    Commented Jun 13, 2016 at 7:49
  • \$\begingroup\$ How does this handle overflow? It's easy to imagine a scenario where z (122) gets a number >=5 added to it. \$\endgroup\$ Commented Jun 14, 2016 at 15:03
  • \$\begingroup\$ @TimmyD I hadn't thought about that... Maybe it could display an \x code? That's what my Python implementation does, but I'm not sure if that will work in some other languages. \$\endgroup\$
    – m654
    Commented Jun 14, 2016 at 15:07

Latin vs Greek vs Cyrillic / Battle of the Alphabets

Meta: This is just a rough draft, the challenge is still under development, feel free to add suggestions as comments or via chat pinging @flawr

Points that are unclear so far:

  • Is there one fixed typeface for all three?
  • Will the image always be provided in the exact horizontal orientation?
  • How long will the provided text be, just single words? A single line? A multiline piece of text?

These three alphabets are relatively similar and even have some letters in common, but also a lot of distinct letters. In this challenge, you have to write a classifier that can distinguish these three alphabets, when presented with a raster image of a corresponding text.

This is an image from Wikipedia that shows the differences in the capital letters:

enter image description here

This challenge was inspired by this message.

  • 2
    \$\begingroup\$ What about ambiguity? Expected output for POTATO, COMA, or TAXONOMY? \$\endgroup\$
    – Geobits
    Commented Jun 15, 2016 at 14:03
  • \$\begingroup\$ Good point, then all outputs are correct. But I had longer pieces of texts in mind, like multiple lines, but now I'm thinking perhaps just single words would be easier. What would you say? \$\endgroup\$
    – flawr
    Commented Jun 15, 2016 at 15:39
  • 1
    \$\begingroup\$ I'd prefer the input to be a single letter, and the correct output to list all alphabets where it belongs, with score being number of correctly classified letters in a test battery (secondary goal is byte count). That may be vulnerable to hashing tricks though. Maybe the letters could also be randomly scaled to, say, 90% to 110%? \$\endgroup\$
    – Zgarb
    Commented Jun 16, 2016 at 7:53
  • 1
    \$\begingroup\$ @Zgarb it's still easy to get 100% with computer vision classifiers if there is only one nicely cropped letter as input and all test images have the same exact font as the one used in training \$\endgroup\$
    – Fatalize
    Commented Jun 17, 2016 at 8:09
  • \$\begingroup\$ I agree, thats why I'd use at least full words or lines. \$\endgroup\$
    – flawr
    Commented Jun 17, 2016 at 8:36

Don't let those functions get away


My imaginary language, PremOpt discourages the use of functions. They are the source of every performance problem. Your task today is to fix beginner PremOpt programmer's code.

Every statement's and loop's (if, switch, while, for) content is enclosed in brackets:

<if/switch/while/for> <statement here> {

Switch cases are one liners:

switch <value> {
    case <val1>: <statement1>;
    case <val2>: <statement2>;
    case <val2>: <statement2>;

Functions look like these:

function <name>(arg1, arg2, arg3) {
    // Stuff here

// Calling a function:
<name>(arg1, arg2, arg3);

Other lines end with a semi-colon.

Variables don't need to be declared, they're already initialized to null, you can set a variable to a value with

variableName = value;

Outputting a value is done by doing



Your input is a string with a piece of code. Each row is separated with a line-feed. The input may or may not contain functions.


You need to remove the functions from the code, and put their content to the where they were called.


function hello() {



Multiple function calls:

function func() {



If the function takes in arguments:

function argFunc(arg1, arg2) {
argFunc(myVar1, myVar2);
argFunc(myVar3, myVar4);

then you need to change the arguments inside the function to match with the calling arguments


Test cases

fibonacci sequence:

a = 1;
b = 1;
function getNextNumber(num1, num2) {
    return num1 + num2;

while(true) {
    a = getNextNumber(a, b);
    b = getNextNumber(a, b);

Should become

a = 1;
b = 1;

while(true) {
    a = a + b;
    b = a + b;


for (counter = 0; counter <= 100; counter++) {

function checkNumber(num) {
    if (num % 3 == 0  num % 5 == 0) {
        out->"Fizz Buzz";
    } else if (num % 3 == 0) {
    } else if (num % 5 == 0) {
    } else {


for (counter = 0; counter <= 100; counter++) {
    if (counter % 3 == 0  counter % 5 == 0) {
        out->"Fizz Buzz";
    } else if (counter % 3 == 0) {
    } else if (counter % 5 == 0) {
    } else {


  • There'll be no recursive functions in the input
  • Standard loopholes are forbidden
  • \$\begingroup\$ This grammar doesn't seem to be well defined enough for this to not be too broad. What about functions in functions? What kinds of literals are expected to be supported? Can functions have the same name but different arguments? What operators have to be supported (specifically w.r.t. functions, like myFun(++foo)++)? What about functions that return things but have more than one operations, but are in a heavily nested statement? This is all just from the top of my head, there are likely more such problems. I think you would need to heavily simplify the language for this to be a good question. \$\endgroup\$ Commented Jun 28, 2016 at 12:58

fix show

Your task is given n, you must print first n character returned from Haskell expression fix show.

Let me explain how fix show produces the "magic" string.

show is just escaping the string and then add quote. Since the resulting string consists only double quotes and backslash, show then essentially just put backslash before every character then quote the resulting string.

show str = '"' : concat ( zipWith (\x y->[x,y]) (repeat '\\') str ) ++ "\"" -- Well, this is not what prelude give, but

fix is, well, fixpoint combinator. But thanks for laziness, it won't do a infinite loop first.

The string is equivalent to the string defined below:

Assuming there is a series of string. The first string is "" and the next series is just application of show to previous string:

"" "\"\"" "\"\\"\\"\"" "\"\\"\\\\"\\\\"\\"\"" "\"\\"\\\\"\\\\\\\\"\\\\\\\\"\\\\"\\"\""

For all n, there is k so that for all l above k, n-th character of l-th string from series is same. That character is the n-th character of fix show

TODO: I hate the sentence above, please fix it.

The first 100 character in resulting string


So, another implementation is

fixshow = '"' : zip (repeat '\') fixshow ++ "\""


  1. You are not allowed to use function fix, show, and the equivalent functions.
  2. Shortest answer wins.

Sandbox question

Is there another way to prevent answer like flip take$fix show, or without importing f k=k$f k;j n=take n$f show. And how about array programming language like APL, J and Jelly?

  • \$\begingroup\$ Your construction doesn't work because zip doesn't intersperse the characters, but creates a list of tuples. I think the backslashes also need escaping. It would be helpful to explain that the number of backslashes in sequence goes 1,3,7,15,... with numbers one less than powers of two. It would be a shame to eliminate all languages with lazy evaluation or generators. It's also vague. Python has generators but they are totally useless here. Even Haskell needs a costly import to get fix. \$\endgroup\$
    – xnor
    Commented Jun 1, 2016 at 3:52
  • 1
    \$\begingroup\$ The output should start "\"\\\"\\\\\\\"\\\\\\\\\\\\\\\". \$\endgroup\$
    – xnor
    Commented Jun 1, 2016 at 3:58
  • \$\begingroup\$ Language-specific questions are not likely to make much challenge acceptors. \$\endgroup\$ Commented Jun 3, 2016 at 7:25
  • \$\begingroup\$ @EʀɪᴋᴛʜᴇGᴏʟғᴇʀ This question isn't language specific, it just involves implementing a particular Haskell program in any other language. That said, it was a bit hard to figure out what was going on as someone who doesn't really know Haskell. \$\endgroup\$ Commented Jun 3, 2016 at 13:18
  • \$\begingroup\$ @FryAmTheEggman This should be closed as "unclear what you're asking". \$\endgroup\$ Commented Jun 3, 2016 at 13:55
  • \$\begingroup\$ seems like a cool challenge, but instead of trying to explain lazy evaluation, just define show rigorously, and then say the challenge is to output the limit of applying show n times on the empty string. also, your output is wrong. \$\endgroup\$ Commented Jun 3, 2016 at 18:46
  • \$\begingroup\$ @proudhaskeller when you say the limit of applying show n times, do you mean result of applying show infinite times on ""? \$\endgroup\$
    – Xwtek
    Commented Jun 4, 2016 at 15:21
  • \$\begingroup\$ @xnor 1. I just hate the answer flip take$fix show. How do I avoid it? 2. Fixed. \$\endgroup\$
    – Xwtek
    Commented Jun 4, 2016 at 15:24
  • \$\begingroup\$ @ChristianIrwan no, because there is no such thing, applying infinite times. instead, if you have a series of strings, first the empty string, then applying once, then twice, and so on, and at each string look at the ith character, from some point on it will be identical in all the strings of the series, and the ith character of the limit will be this character. \$\endgroup\$ Commented Jun 4, 2016 at 15:29
  • \$\begingroup\$ @proudhaskeller Oh, I see. Thanks. \$\endgroup\$
    – Xwtek
    Commented Jun 4, 2016 at 16:04
  • \$\begingroup\$ The implementation with zipWith. Maybe you could just ban the command show and equivalents? I think implementing it and a a pseudo-fix would be interesting and not definitely better than concatenating powers-of-2-sized blocks. \$\endgroup\$
    – xnor
    Commented Jun 5, 2016 at 2:54
  • \$\begingroup\$ *The implementation with zipWith doesn't work. \$\endgroup\$
    – xnor
    Commented Jun 5, 2016 at 21:58

Golfing with ultrasound

Within medical physics, the percentage of ultrasound reflected between material boundaries can be calculated using two pieces of data: the density(p) and the speed(c) at which sound travels through the material.

To calculated the percentage reflection the following equation can be used

(Z1-Z2)^2 / (Z1+Z2)^2

Where Z1 and Z2 are the acoustic impedances(Z) of the two materials. Z is calculated such that Z=pc That is density * speed of sound in the material

This is where the issue lies

I have two ways of asking the question


Given the acoustic impedance for two materials, calculate the percentage reflection.


Given the density and speed of sound in two materials, calculate the percentage reflection


The first method will be much simpler, in the way you are just plugging values into a formula. However I feel that method 2 is heavy on the inputs, and I understand that four inputs is a large number of inputs in golfing challenges

On posting the question I will also add a number of test cases

  • \$\begingroup\$ Firstly, I think you should add test cases while it's still in the sandbox. I find it's easy to miss important ones. In your formula you say Z=pc. What is c? I think you should add some formatting to your formulas, as they are a bit hard to read. You could also consider using some TeX service to generate an image of the formula for you. Also, density is usually denoted by ρ. \$\endgroup\$ Commented Jun 29, 2016 at 19:38
  • \$\begingroup\$ I was going to use rho, but I didn't know where to find one. In hind sight I could have copied and pasted from Wikipedia. Speed should have been given as c not v. But I will make clear what I mean by Z=pc. What is TeX? I've not heard of it before? \$\endgroup\$
    – george
    Commented Jun 29, 2016 at 19:41
  • \$\begingroup\$ TeX is a very popular typesetting program, most of your textbooks were probably made using some variant of it. For example, go to this site and enter \frac{(Z_1-Z_2)^2}{(Z_1+Z_2)^2} as the text. You should see a much easier to read version of your formula as an image. \$\endgroup\$ Commented Jun 29, 2016 at 19:45
  • \$\begingroup\$ @FryAmTheEggman Wow that's a really cool website, thanks! I will edit the question soon and hopefully it will be better \$\endgroup\$
    – george
    Commented Jun 29, 2016 at 19:50
  • 1
    \$\begingroup\$ With either option, it looks like there's a direct mathematical formula that leaves little to golf. \$\endgroup\$
    – xnor
    Commented Jun 29, 2016 at 22:45
55 56
58 59

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .