What is the Sandbox?

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

To post to the Sandbox, scroll to the bottom of this page or click on the "Add Proposal" link below, 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. 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, replace the post here with a link to the challenge and delete it.

See the Sandbox FAQ for more information on how to use the Sandbox.

The Sandbox works best if you sort posts by "active".

Add Proposal

Search the Sandbox

Browse your pending proposals

Get the Sandbox Viewer to view the sandbox more easily

To add an inline tag to a proposal use shortcut link syntax with a prefix: [tag:king-of-the-hill]

  • 2
    \$\begingroup\$ Suggestion: instead of having a notice on the top answer ("note: if you are..."), you'd better just put a moderator notice below the question \$\endgroup\$ – nicael Mar 19 '18 at 19:35
  • 3
    \$\begingroup\$ @nicael We can only choose from three post notices: citation needed, current event, and insufficient explanation. \$\endgroup\$ – Dennis Apr 7 '18 at 14:43
  • \$\begingroup\$ If you remove a post but didn't post it you can replace the text body with [](lots of text here to reach the min chars) to make it much smaller when removed \$\endgroup\$ – Christopher Apr 13 '18 at 17:54
  • 5
    \$\begingroup\$ @Christopher Please don't do that for old proposals. It clutters the first page with an answer nobody cares about anymore, instead of staying hidden on page 10 where it will bother nobody. \$\endgroup\$ – Dennis Apr 13 '18 at 18:17
  • \$\begingroup\$ @Dennis ? what are you talking about. As if if you didn't post it like you just removed you own sandbox because dupe or something \$\endgroup\$ – Christopher Apr 13 '18 at 18:18
  • 4
    \$\begingroup\$ @Christopher If your proposal is still on the first few pages, you can replace the proposal with a stub to save vertical space on these pages. However, if your proposal is already on page 10, editing your proposal will bump it to page 1, where space is more precious than on page 10. \$\endgroup\$ – Dennis Apr 13 '18 at 18:21
  • \$\begingroup\$ @Dennis ohh that makes sense \$\endgroup\$ – Christopher Apr 13 '18 at 18:25
  • \$\begingroup\$ codegolf.meta.stackexchange.com/questions/12599/… \$\endgroup\$ – Redwolf Programs Apr 17 '18 at 17:38
  • 1
    \$\begingroup\$ Maybe it's time to consider cleaning some of this up a bit. There's just too much to go through and some of these proposals are years old and obviously not going anywhere (even some of the good ones). Perhaps cull anything that is two years old and has likewise been inactive for as long? \$\endgroup\$ – ouflak Aug 6 '18 at 9:07
  • 1
    \$\begingroup\$ @ouflak You can sort posts by "active". That seems to resolve all of the problems you describe. \$\endgroup\$ – FryAmTheEggman Sep 27 '18 at 19:04
  • \$\begingroup\$ I already posted this, but codegolf.stackexchange.com/questions/176599/… \$\endgroup\$ – 2br-2b Nov 27 '18 at 2:38
  • \$\begingroup\$ How are tags added to questions? \$\endgroup\$ – guest271314 Jan 9 at 7:51
  • \$\begingroup\$ It seems like there is a rollback war with moderators and the Community user to add and remove the featured tag. \$\endgroup\$ – smileycreations15 Mar 21 at 21:13
  • 3
    \$\begingroup\$ @smileycreations15 That's unfortunately unavoidable. Community is an automatic script, and, since most featured questions are only temporarily so, it assumes that we don't want this question to be featured forever. However, we do, so a mod has to edit the tag in every now and then. \$\endgroup\$ – Erik the Outgolfer Mar 24 at 15:22
  • 3
    \$\begingroup\$ @EriktheOutgolfer Yeah. Maybe they can create a special [featured-pin] tag which will both feature it and pin it from removal by the Community user. \$\endgroup\$ – smileycreations15 Mar 24 at 17:20

2450 Answers 2450


Part I: Triangular Manhattan Distance

Part II: Triangular Chebyshev Distance

The Chebyshev distance on a regular grid is the number of orthogonal or diagonal steps one needs to take to reach one cell from another. That is, we can move either through the edge of a cell, or through a corner, to a neighbouring cell.

We can define a similar distance on other grids, for example the triangular grid. We can address the individual cells in the grid with the following indexing scheme, where each cell contains an x,y pair:

   /\      /\      /\      /\      /\
  /  \ 1,0/  \ 3,0/  \ 5,0/  \ 7,0/  \
 / 0,0\  / 2,0\  / 4,0\  / 6,0\  / 8,0\
\      /\      /\      /\      /\      /
 \ 0,1/  \ 2,1/  \ 4,1/  \ 6,1/  \ 8,1/
  \  / 1,1\  / 3,1\  / 5,1\  / 7,1\  /
   /\      /\      /\      /\      /\
  /  \ 1,2/  \ 3,2/  \ 5,2/  \ 7,2/  \
 / 0,2\  / 2,2\  / 4,2\  / 6,2\  / 8,2\  
\      /\      /\      /\      /\      /
 \ 0,3/  \ 2,3/  \ 4,3/  \ 6,3/  \ 8,3/
  \  / 1,3\  / 3,3\  / 5,3\  / 7,3\  /
   /\      /\      /\      /\      /\
  .  .    .  .    .  .    .  .    .  .
 .    .  .    .  .    .  .    .  .    .

Now the Chebyshev distance on this grid is again the minimal number of steps across edges or corners to get from one cell to another. So you can move from 3,1 to any of its 12 neighbours:

2,1 4,1 3,2 (through edges)

3,0 1,2 5,2 (the opposite triangle through corners)

2,0 4,0 1,1
5,1 2,2 4,2 (the other triangles through corners)

For instance, the distance from 2,1 to 7,2 is 3. The shortest path is generally not unique, but one way to make the distance in 3 steps is:

2,1 --> 4,1 --> 5,1 --> 7,2

The Challenge

Given two coordinate pairs x1,y1 and x2,y2 from the above addressing scheme, return the Chebyshev distance between them.

You may assume that all four inputs are non-negative integers, each less than 128. You may take them in any order and arbitrarily grouped (four separate arguments, a list of four integers, two pairs of integers, a 2x2 matrix, ...).

You may write a program or a function and use any of the standard methods of receiving input and providing output.

You may use any programming language, but note that these loopholes are forbidden by default.

This is , so the shortest valid answer – measured in bytes – wins.

Test Cases

Each test case is given as x1,y1 x2,y2 => result.

1,2 1,2 => 0
0,1 1,1 => 1
1,0 1,1 => 1
2,1 7,2 => 3

Will add more test cases when I have a reference implementation.

  • \$\begingroup\$ @trichoplax Yes, thank you. With the slow response to the Manhattan variant, I do wonder whether this one will be a bit too tricky, but we'll see. :) \$\endgroup\$ – Martin Ender Apr 4 '17 at 21:28
  • \$\begingroup\$ "I do wonder whether this one will be a bit too tricky, but we'll see. :)" I've found a solution for this one, but not for the other one yet. ;) \$\endgroup\$ – Kevin Cruijssen Apr 5 '17 at 12:01
  • \$\begingroup\$ @KevinCruijssen Oh, would you mind sharing it? :) \$\endgroup\$ – Martin Ender Apr 5 '17 at 12:06
  • \$\begingroup\$ I always make my answers in Java 7 btw, so I'll still be beaten by golfing answers. But this is what I came up with (I've also added an explanation of how I came up with the solution in the TIO footer): Try it here. \$\endgroup\$ – Kevin Cruijssen Apr 5 '17 at 12:23
  • \$\begingroup\$ Hmm, I just took another look at your part 1 challenge and realized my solution above for part 2 is incorrect.. :( Based on your current test cases I falsely assumed x1,y1 is always smaller than x2,y2. So my code fails for a test case like 4,1 1,3. Back to the drawing board.. Also, as to why I think this challenge is easier than part 1: In part 1 you had to determine whether the triangle was facing upwards (available: left; right; below) or facing downwards (available: left; right; above). With this challenge all 12 surrounding triangles - regardless of orientation - are accessible. \$\endgroup\$ – Kevin Cruijssen Apr 7 '17 at 8:22
  • \$\begingroup\$ @KevinCruijssen but the exact coordinates/orientations of those 12 neighbours also change, right? \$\endgroup\$ – Martin Ender Apr 7 '17 at 8:24
  • \$\begingroup\$ Yeah, was about to edit my comment again when I realized that.. If you have more test cases I'll take another look at this part 2. I'll start with part 1 for now. (PS: Have a nice weekend - apparently I can use it.. >.>) \$\endgroup\$ – Kevin Cruijssen Apr 7 '17 at 8:25
  • \$\begingroup\$ Me again, more than one year later. I've currently set a bounty for your Part 1 challenge to give it more attention, which you may or may not have noticed based on the new answers given. If you have time, could you add more test cases for this one? \$\endgroup\$ – Kevin Cruijssen Jun 29 '18 at 8:40
  • \$\begingroup\$ @KevinCruijssen I'm not sure how soon I'll get around to that, because I'd want to write a reference implementation for that. If you want it post it soon, feel free to add them yourself (and optionally post the challenge yourself if you like). \$\endgroup\$ – Martin Ender Jun 29 '18 at 16:26
  • \$\begingroup\$ Oh no, I'll patiently wait. I'm going on vacation soon anyway, so I won't have time to answer during that time. I just made that comment above as a reminder so it can hopefully be posted in the not to distant future. :) \$\endgroup\$ – Kevin Cruijssen Jun 29 '18 at 16:42

Mark Duplicates

Given a list of non-negative integers, find the values which are duplicates and mark their positions.

For example, given [1, 2, 3, 2, 1], the output could be [1, 1, 0, 1, 1] where each 1 signifies that the value at that position is duplicated elsewhere in the array and each 0 signifies that the value at that position is unique.

Your output may use either 0 and 1, boolean values for false and true, or any other two distinct values as long as you remain consistent.

This is so minimize the length of your code.

Test Cases

[] -> []
[5] -> [0]
[0, 1] -> [0, 0]
[2, 2] -> [1, 1]
[1, 2, 3, 2, 1] -> [1, 1, 0, 1, 1]
[6, 3, 6, 3, 5, 2, 3] -> [1, 1, 1, 1, 0, 0, 1]
  • 2
    \$\begingroup\$ Ironically, I feel this is a duplicate of (or at least closely related to) and existing challenge but I can't find it at the moment. \$\endgroup\$ – Shaggy May 24 '17 at 10:43
  • \$\begingroup\$ Would we have to use 0 & 1 or could we use any 2 distinct & consistent values? \$\endgroup\$ – Shaggy May 24 '17 at 11:06
  • \$\begingroup\$ I.e Nub Sieve? \$\endgroup\$ – Adám May 24 '17 at 11:27
  • \$\begingroup\$ @Adám I previously made a challenge for nub sieve. This is slightly different since we aren't choosing positions to filter for only the unique values. \$\endgroup\$ – miles May 24 '17 at 18:43
  • 1
    \$\begingroup\$ @Shaggy Yes, any choice of output values is fine as long as its two distinct values that you use consistently. \$\endgroup\$ – miles May 24 '17 at 18:45
  • \$\begingroup\$ Isn't this just NOT nub sieve? \$\endgroup\$ – Adám May 24 '17 at 18:47
  • \$\begingroup\$ @Adám For the [1, 2, 3, 2, 1], nub sieve could be [1, 1, 1, 0, 0], [0, 1, 1, 0, 1], [0, 0, 1, 1, 1], [1, 0, 1, 1, 0], and the not of each is [0, 0, 0, 1, 1], [1, 0, 0, 1, 0], [1, 1, 0 ,0, 0], [0, 1, 0, 0, 1]. \$\endgroup\$ – miles May 24 '17 at 19:21
  • \$\begingroup\$ I think this would be interesting if the first time an entry appears it's not counted as a duplicate. \$\endgroup\$ – xnor May 24 '17 at 19:37
  • \$\begingroup\$ @xnor Wouldn't that be not( nub-sieve( x ) )? \$\endgroup\$ – miles May 24 '17 at 20:23
  • \$\begingroup\$ How does nub-sieve work? My suggestion is because it means the position of the item matters rather than just its value, so it's not just mapping each entry x to l.count(x)>1. \$\endgroup\$ – xnor May 24 '17 at 20:26
  • \$\begingroup\$ The first occurrence of a value is marked true and all subsequent occurrences of the same value are marked false. Nub-sieve. My previous challenge for distinct sieves is a relaxed variant to nub-sieve. For [1, 2, 3, 2, 1], a proper nub-sieve would be [1, 1, 1, 0, 0], and not of that would be [0, 0, 0, 1, 1]. I do agree with that last sentence about how most solutions in golfing languages would probably just count occurrences. \$\endgroup\$ – miles May 24 '17 at 20:44
  • \$\begingroup\$ @miles can I adopt and post this abandoned proposal? \$\endgroup\$ – programmer5000 Jun 9 '17 at 1:34

Table parser, code golf


|Left align |  Right align| Center align |
|This       |         This|     This     |
|                column                  |
|will       |                            |
|-----------|          will be           |
|be         |                            |
|left       |        right|    center    |
|aligned    |      aligned|   aligned    |
|and can be |    vertical-|              |
|multilined | align middle|  as default but a bit long line |
|with <br>  |             |              |

Output should be valid HTML. And I am thinking of following requirement specs.

  • alignments (left, right, middle)
  • border thickness (normal -, |, bold, =,||)
  • with table headers or without
  • rowspans, colspans
  • multiline & vertical-align is always middle

What do you think?

  • \$\begingroup\$ I guess figuring out cells and row/colspans is enough work, so handling bold and italic could be omitted, maybe. \$\endgroup\$ – Joey May 9 '11 at 12:15
  • \$\begingroup\$ Also, should this be a code golf or a challenge? \$\endgroup\$ – Joey May 9 '11 at 12:18
  • \$\begingroup\$ code-golf @joey. and I am gonna leave bold and italic out. I was not sure it was hard enough :D \$\endgroup\$ – YOU May 9 '11 at 13:22
  • \$\begingroup\$ Can cells contain more than a line of text? I.e. do long contents wrap or do they extend the cell? \$\endgroup\$ – Joey May 9 '11 at 13:35
  • \$\begingroup\$ @Joey, yeah, a bit more complicated now, multiline involve vertical-align, so I set that as middle as default, what do you think? \$\endgroup\$ – YOU May 9 '11 at 13:49
  • \$\begingroup\$ Yikes :D. Well, I was just pondering a few ways of figuring out the layout and determining rowspans would be much easier if all rows are the same height ;). Should be ok, but bear in mind that it makes judging correct vertical align difficult. Given the current last row the valigns could be either one of mmm, ttm, tmm, btm, bmm. No show-stopper but something to keep in mind for test cases and scripts. \$\endgroup\$ – Joey May 9 '11 at 13:53
  • \$\begingroup\$ @Joey, yeah, to judge top, middle, and button, we need a blank row between every table row, just like a space in right, right, and center, so I guess I need to make vertical-align as middle as default. \$\endgroup\$ – YOU May 9 '11 at 14:06
  • \$\begingroup\$ So vertical align will not vary and always be middle, if I understand you correctly? \$\endgroup\$ – Joey May 9 '11 at 14:07
  • \$\begingroup\$ @Joey, yeah .. and for multiline items you just need to put <br> between and can be, multilined, and too, if those are supposed to be same line, input will be |and can be multilined too | ....... | ..... | . \$\endgroup\$ – YOU May 9 '11 at 14:10
  • \$\begingroup\$ I think your multi-column cells are ambiguous: the last row shows that text can extend beyond the ASCII art column width, so we cannot use the horizontal alignment of |s to judge colspans. Therefore, the 4th and 5th rows could span 1 and 2 columns (as visually, but unreliably indicated) or 2 and 1 columns. Example \$\endgroup\$ – Adám Jun 5 '17 at 7:20
  • \$\begingroup\$ @Adám, thanks for taking a look. Yeah, might be that's the reason there is not much interest on this. \$\endgroup\$ – YOU Jun 5 '17 at 10:33
  • \$\begingroup\$ @YOU Also, this is a very complex challenge, pretty much implementing a large subset of the Wiki markup for tables. Maybe you should narrow the scope by removing all formatting; alignment, borders, headers (these are also ambiguous), and just focusing on converting the -| style table into HTML. Maybe even remove the row and column spans? \$\endgroup\$ – Adám Jun 5 '17 at 10:42
  • \$\begingroup\$ I don't remember why I put all those things in, may be similar challenge was there already, for simple tables, but I don't know. I need to look up more. \$\endgroup\$ – YOU Jun 5 '17 at 14:11
  • \$\begingroup\$ @Adám, removed rowspan, colspan, multiline and vertical align. Not sure it could be duplicate entry now. \$\endgroup\$ – YOU Jun 5 '17 at 14:17
  • 1
    \$\begingroup\$ @programmer5000, became duped, because of you guys suggestion. I rollbacked. \$\endgroup\$ – YOU Jun 9 '17 at 15:37

Line up for golf!

  • 4
    \$\begingroup\$ The comments in the test cases reduce their usefulness as test cases. Moreover, the first one contradicts the "full specification", and the second one adds to it. The spec should contain everything needed to justify the correctness of the test cases. You also need to specify desired behaviour when there is no solution, and to include a test case for that scenario. \$\endgroup\$ – Peter Taylor Mar 7 '14 at 14:04
  • 2
    \$\begingroup\$ How are conditionals to be interpreted when mixed in a single full condition? Alice is 1st or 1st to last and in front Bob or 1 space behind Bob \$\endgroup\$ – John Dvorak Mar 7 '14 at 14:12
  • \$\begingroup\$ This seems like a good challenge, but Peter Taylor and Jan Dvorak's concerns should be addressed. \$\endgroup\$ – Hosch250 Mar 8 '14 at 18:42
  • \$\begingroup\$ @PeterTaylor Edited, but how does the first one contradict? \$\endgroup\$ – Doorknob Mar 10 '14 at 2:32
  • \$\begingroup\$ @JanDvorak Edited to clarify. \$\endgroup\$ – Doorknob Mar 10 '14 at 2:32
  • \$\begingroup\$ Another concern: What if there is no solution? What if there is more than one? \$\endgroup\$ – John Dvorak Mar 10 '14 at 6:04
  • \$\begingroup\$ Please delete this now that it is posted. \$\endgroup\$ – programmer5000 Aug 1 '17 at 16:07

This message is open for anyone to adopt and post to main. For more details, see the chat room or meta post.

Ping an IP address continually and report the dropped to returned ratio

Create a console program that pings an IP address at most once per second and reports the ratio of dropped to returned packets to the screen in real time.

The IP address will be provided on the command line in standard IPv4 notation. (eg.

The 'ping' method should be ICMP echo (See here for a summary of ICMP packet structure) with a packet size of at least 32 bytes.

Your program must be "standalone" and cannot rely on external programs, libraries, or resources.

This is so let the shortest answer win

  • \$\begingroup\$ ping isn't enough? \$\endgroup\$ – TheDoctor Apr 7 '14 at 19:31
  • \$\begingroup\$ ping works great, except you have to tell it when to stop to get the final tally \$\endgroup\$ – David Wilkins Apr 7 '14 at 19:32
  • \$\begingroup\$ I think you're assuming that everyone will interpret this as sending the same ICMP control packet that ping sends, but it would be an improvement to the question both to make this explicit and to link to some documentation about ICMP. \$\endgroup\$ – Peter Taylor Apr 7 '14 at 22:46
  • \$\begingroup\$ Actually I left it ambiguous. Any IP request that elicits a response can be considered a ping. \$\endgroup\$ – David Wilkins Apr 8 '14 at 1:00
  • \$\begingroup\$ Alright, lets make it easier and say ICMP specifically... \$\endgroup\$ – David Wilkins Apr 8 '14 at 12:16
  • \$\begingroup\$ Well this doesn't have enough upvotes...I'll leave it in the sandbox, but likely it will not be posted \$\endgroup\$ – David Wilkins Apr 9 '14 at 12:17
  • \$\begingroup\$ Hello! This looks like a good but abandoned meta post, would you be willing to offer it for adoption? (If you want to, you can still post to main.) Due to community guidelines, if you don't respond to this comment in 7 days I have permission to adopt this. \$\endgroup\$ – programmer5000 Jun 9 '17 at 16:34
  • \$\begingroup\$ @programmer5000 be my guest :) \$\endgroup\$ – David Wilkins Jun 9 '17 at 16:40

This is a proposal adopted by programmer5000. Any feedback before I post it?

Seven-segment usage

I have an old digital clock and I am concerned the individual segments of the digits might run out of magical binary energy or whatever powers them. To know which of the segments on the clock will fail first I want to know what is the percentage of time each segment is lit.

The challenge is to compute the percentage of time any segment on a digital clock is lit.


The input will be in the form X.L, where:

  • X is a number from 1 to 4. 1 is the left-most number of the clock, 4 the right-most
  • L is a letter from a to g or a number from 1 to 7
  • the separator can be changed to fit your needs (no separator is an option)

Disposition of segments, image source: Wikipedia Disposition of segments plus numbers image source: Wikipedia]


The output, is a percentage, given with at least 2 figures after the decimal point. It can be rounded or truncated to the closest value if you want to keep a limited number of digits.

Valid outputs: 0.74, 32.47, 7.5 (for 7.50)

Additional stuff

The clock is in 24 hours format (so 22:45 is a valid time).

We consider the clock started working at 0:00 so the challenge is effectively working out what percentage of a complete day a single segment is lit.

The first number is not lit when it is 0.

Lit segments for each number:

  • 1: b c
  • 2: a b d e g
  • 3: a b c d g
  • 4: b c f g
  • 5: a c d f g
  • 6: a c d e f g
  • 7: a b c
  • 8: a b c d e f g
  • 9: a b c d f g
  • 0: a b c d e f


  • 1.b => 58.33
  • 3.e => 33.33
  • 2.d => 70.83
  • 4.d => 70.00

Full list of outputs here


Code golf, most probably, though I am not sure yet this is the best format (I am not too interested in the input parsing and the output formatting, they might be an obstacle to golfing?)

  • 6
    \$\begingroup\$ AIUI there are 28 valid inputs, so you could provide a full list of test cases as a pastebin. I would remove "No hard coding of results": if hard-coding the 28 cases is shorter than the calculation, then IMO that's a flaw which makes the question not worth bothering with at all rather than something which can be worked around; and the issue of whether or not an answer "hard-codes the results" is likely to be grey rather than black or white. \$\endgroup\$ – Peter Taylor Mar 3 '16 at 10:54
  • \$\begingroup\$ List of results added, I'll need to double check them. Hard coding removed, yes I don't see how "cheating" would be an issue. Any hard-coding would have to be quite constructive to be efficient. \$\endgroup\$ – drolex Mar 3 '16 at 11:29
  • \$\begingroup\$ I am removing limitations on the output as well, I don't think it brings anything to the challenge. I have started to golf a solution in python, I think there are a few interesting possibilities to optimise the use of strings describing segments used for each digit. \$\endgroup\$ – drolex Mar 3 '16 at 15:56
  • \$\begingroup\$ Can I post this abandoned proposal? \$\endgroup\$ – programmer5000 Jun 9 '17 at 13:00
  • \$\begingroup\$ @programmer5000 certainly, just try to make it better :) \$\endgroup\$ – drolex Jun 9 '17 at 13:05

What is your Operating System?

I can't believe we haven't had this one before

To avoid any doubts about what constitutes a separate OS, you must return an index into your chosen subset (containing minimum two) of the following OS families. You may order your set as you like, so include your ordered set, and state if you use zero or one based indexing. You may also bunch together families you cannot distinguish between.

  Windows, Minix, Linux, macOS, BSD, HP-UX, AIX, Solaris, Unix, Z/OS, OS/2, QNX

Your score is your byte count divided by the square of the number of indices your code can return – given that it is run on the appropriate OSs, of course.

You do not have to account for virtual machines, emulation layers etc., e.g. WSL and Wine.


Your code can detect Windows, macOS, AIX, and Linux. It returns 0 for Windows, 1 for macOS, 2 for AIX, and 3 for Linux. Your score is a sixteenths of your byte count.

Your code can distinguish between Z/OS, OS/2, and UNIX/Linux/AIX. It returns 1 for Z/OS, 2 for OS/2, and 3 for any UNIX-like OS. Your score is a ninth of your byte count.

  • \$\begingroup\$ 2 is definitely better than 1. After that I think it may just be your preference for the kinds of answers you want. I think 3 will promote more answers that reach, while 2 will promote more 2 answers. However, if you really want to reach maybe make the denominator grow as a square? These scoring mechanisms are unfortunately very important to these kinds of challenges as well as very hard to figure out beforehand. I'd ask around and see what other people think! \$\endgroup\$ – FryAmTheEggman Jun 15 '17 at 0:37
  • \$\begingroup\$ @FryAmTheEggman Thanks. \$\endgroup\$ – Adám Jun 15 '17 at 0:39
  • \$\begingroup\$ Are not macOS, BSD, and Linux Unix? Is OSX considered the same as macOS? \$\endgroup\$ – Sriotchilism O'Zaic Jun 21 '17 at 14:53
  • \$\begingroup\$ The I/O requirements are rather strict, could you not just print/return the name of the OS? \$\endgroup\$ – musicman523 Jun 21 '17 at 14:56
  • \$\begingroup\$ @WheatWizard Yes, but you may pick whichever many you want from that list, so you can bunch all Unixes together or keep them separate, or you can detect specific flavors while also detecting vanilla Unix. \$\endgroup\$ – Adám Jun 21 '17 at 15:02
  • \$\begingroup\$ @musicman523 I'd rather have comparable output from all solutions. \$\endgroup\$ – Adám Jun 21 '17 at 15:03
  • 3
    \$\begingroup\$ It seems like people with access to proprietary OSs will have an advantage in this problem. For example, to ensure my code runs on Windows I have to buy windows, because I don't own it. I happen to own a copy of OSX, but other users might not given me an advantage. I feel like this is problematic. (also is OSX considered the same macOS?) \$\endgroup\$ – Sriotchilism O'Zaic Jun 21 '17 at 15:09
  • \$\begingroup\$ @WheatWizard You're right, but that will be problematic in detection of OSs no matter what the challenge is. And yes, good luck testing your solution on Z/OS… \$\endgroup\$ – Adám Jun 21 '17 at 15:34
  • \$\begingroup\$ It's not just that. If I claim to detect Windows, which versions of Windows do I have to test it on? And what can I assume about e.g. the C header files that are available? \$\endgroup\$ – Peter Taylor Jun 21 '17 at 15:35
  • \$\begingroup\$ @WheatWizard Oh, and yes, OSX and macOS are the same (I don't expect anyone to submit an answer that will run on MacOS 9-) \$\endgroup\$ – Adám Jun 21 '17 at 15:35
  • \$\begingroup\$ @PeterTaylor Good point. Any ideas how to fix this or is it doomed? \$\endgroup\$ – Adám Jun 21 '17 at 15:36
  • 1
    \$\begingroup\$ I suspect that the difficulties around specification and testing might explain why this hasn't been asked already. \$\endgroup\$ – Peter Taylor Jun 21 '17 at 15:44
  • \$\begingroup\$ Why numbers only? Why not just outputs? \$\endgroup\$ – CalculatorFeline Jun 21 '17 at 16:00
  • 1
    \$\begingroup\$ Is the set of OSes listed there exhaustive? (I've done some programming on SunOS in the past, for example, although I don't have access to it right now.) Also, "Unix" seems a bit strange to have in the list; many of the listed OSes (e.g. BSD and Solaris) are flavours of Unix. It's also worth being aware of cases like WSL and Wine; which OS should they count as? \$\endgroup\$ – user62131 Jun 22 '17 at 10:28
  • \$\begingroup\$ @ais523 "Unix " allows submissions to bunch together various flavors as one, and also allows differentiating the other Unixy OSs from vanilla Unix. I'll add a note about virtual machines etc. \$\endgroup\$ – Adám Jun 22 '17 at 14:54

A Game of Knights

In this King of the Hill, you control 10 Knights. You need to surround your enemy before they surround you.

Each Knight has 3 possible actions:

  • Dash: Move 3 squares in a cardinal direction. If there is a knight in your path, move as far as you can.
  • Leap: Move 2 squares in a cardinal direction. If there is a knight on your destination square, don't move at all.
  • Push: Move 1 square in a cardinal direction. If there is a knight on your destination square, and no knight or wall behind him, you both move 1 square.

Each round will have a Planning Phase and then an Action Phase.


During the planning phase, players will alternate creating a plan until both players have created 10 plans.

  • A plan consists of either an action type or a cardinal direction (not both).
  • A plan also includes the knight that will perform the action
  • All plans are revealed to both players


  • Actions occur in the same order that they were planned.
  • If you planned an action type, you will be able to choose the direction. If you planned a cardinal direction, you will be able to chose the action type you want.

After the action phase, if any knights are on the same location they started at (at the start of the round) are captured and removed from the game. You win by capturing all other knights.

Other info:

  • Cardinal means North, East, South, or West
  • The board is a 10x10 board. Your knights start as a line at the bottom of the board.
  • Walls block movement and cannot be pushed.
  • You don't have to plan an action for every knight, and a knight can take multiple actions.
  • There are a maximum of 1000 rounds. After those 1000 rounds, the winner is the player with the most knights. (A tie is allowed).
  • The starting player for a game is randomized, and that player starts every round.

You have won the game when you opponent cannot make any mobility actions.

  • 3
    \$\begingroup\$ Man, now I want to play this in person. \$\endgroup\$ – DLosc Feb 18 '17 at 21:17
  • 1
    \$\begingroup\$ Isn't it possible to form your knights into a solid 2×5 rectangle (thus immune to pushing), away from the starting squares, before the enemy can move and push it? That would guarantee you couldn't lose. Also you should clarify whether you can plan two actions for the same knight, and if you can, whether it gets to take both or only one. \$\endgroup\$ – user62131 Feb 18 '17 at 23:14
  • \$\begingroup\$ @ais523 movement is not simultaneous. You start as a 1x10 line. A knight could take 10 moves on a round \$\endgroup\$ – Nathan Merrill Feb 18 '17 at 23:52
  • \$\begingroup\$ To be clear, as long as you have 10 knights, you need to move each of them every round or lose the ones you didn't move, assuming you don't push. Correct? \$\endgroup\$ – isaacg Jun 23 '17 at 21:30
  • \$\begingroup\$ Does the same player go first in each round, or does that alternate? \$\endgroup\$ – Peter Taylor Jun 23 '17 at 21:31
  • \$\begingroup\$ @isaacg correct. \$\endgroup\$ – Nathan Merrill Jun 23 '17 at 23:51
  • \$\begingroup\$ @PeterTaylor I've debated about this, and I think the same player will go first in each round. The player that goes first will be randomized each game, but it will be consistent round to round. Otherwise, you end up with a player being able to move twice in a row. \$\endgroup\$ – Nathan Merrill Jun 23 '17 at 23:52

Invisible Ink, Easy

In the physical world, invisible ink usually becomes invisible when it dries, and is then is readable if it is exposed to heat or chemicals of some kind. The invisible ink in this challenge will be readable when exposed to highlighting.

Create a full program or function that takes in text from the console (using a prompt) and outputs it the console so it cannot be seen unless highlighted.

enter image description here

enter image description here


  • Assume that the console is a solid color (black, white, green, etc.).

Swap the frogs!

Given 2 integers N >= 1, representing left-side frogs, and M >= 1, representing right-side frogs, return all the steps required so that the frogs change sides with the minimum number of steps. The frogs start with one empty spot between the two sides. A frog can jump to the empty space if there is at most 1 frog from either side between the frog and the empty space. A frog can jump either forwards or backwards.

An example, with N = 3 and M = 2:


The corresponding output would be (1-indexed):

[3, 5, 6, 4, 2, 1, 3, 5, 4, 2, 3]

Each one is the index of the column that the frog that must jump is before jumping.


  • You may perform I/O in any reasonable format.
  • 1
    \$\begingroup\$ Maybe start with a small example, because now the main output specification is tucked under a huge block of text, which will be TL;DR for many people. \$\endgroup\$ – Sanchises Aug 8 '17 at 10:52
  • \$\begingroup\$ 1. The questions in the section headed "Sandbox" make no sense because their context has been deleted. Are they still relevant? 2. "What you have to print" should presumably be "What you have to output". 3. "A frog can jump either forwards or backwards" so there should be at least one test case where all optimal paths only involve jumping forwards and at least one where all optimal paths involve jumping backwards. \$\endgroup\$ – Peter Taylor Aug 8 '17 at 14:55
  • \$\begingroup\$ Maybe a testcase where no steps are necessary, too. \$\endgroup\$ – Sanchises Aug 8 '17 at 15:13
  • \$\begingroup\$ @PeterTaylor Please, don't be too meta :-) :p \$\endgroup\$ – Erik the Outgolfer Aug 8 '17 at 16:46

Learning your strengths and weaknesses

  • Fighters have a unique, random Strength (between 1 and 1000)
  • When two fighters fight, the stronger one wins.
  • Your goal is to accurately guess your fighter's Strength.


  1. We start by randomly ordering all 1000 fighters.

  2. Each fighter fights his neighbor (The even fighters fight the fighter 1 above)

  3. The fighter is given two pieces of information: His opponent's last guess, and who won the fight. The fighter then guesses his strength.

  4. We perform a stable sort based on the guessed strength, and go back to step 2

  5. After 10 guesses, the fighter's score is (RealStrength - GuessedStrength)^2. Lower is better.

Other details:

  • There will be duplicate bots in a single game.

  • A stable sort is a sort that (effectively) uses the past ordering as a tiebreaker. In essence, if players [A,B,C,D] guessed [10,5,10,5] then the new order would be [B,D,A,C]

  • Bots aren't allowed to share information between each other, but are allowed to persist information within a single game.

  • I will run a large number of games. The exact number will be dependent on how much variation there is. Your final score will be all of your scores summed up.

  • \$\begingroup\$ I like this a lot. Sounds like a very interesting challenge. A couple thoughts though. 1) What's the point of squaring your score? If there was some kind of polynomial scoring I could see that, but it doesn't really have any purpose at the moment. 2) personally, I think it should be more than 10 rounds. \$\endgroup\$ – DJMcMayhem Jan 29 '18 at 17:17
  • \$\begingroup\$ @DJMcMayhem I think 10 rounds is enough for good bots to get a reasonable score without providing so much information that many will get a perfect score. I do think the process should be repeated though. Maybe a terminology change: 10 guesses per round, each round scored as indicated, average of X rounds is the final score. Also, the squaring is a way of getting absolute value (result is always positive even if guess > real) and if averaging multiple results it weights wildly incorrect guesses to increase the score by a lot. \$\endgroup\$ – Kamil Drakari Jan 29 '18 at 17:45
  • \$\begingroup\$ @DJMcMayhem Squaring means that being 50 off is far worse than being 25 off. I picked 10 rounds because log2(1000) is 9.97. This requires bots to be efficient with their time. If I make it much higher, then its going to be hard for me to differentiate the top bots. \$\endgroup\$ – Nathan Merrill Jan 29 '18 at 18:24
  • \$\begingroup\$ @KamilDrakari Updated, thanks. \$\endgroup\$ – Nathan Merrill Jan 29 '18 at 18:30
  • \$\begingroup\$ In step 3, each fighter is provided "His opponent's last guess". What will be provided during the first round? \$\endgroup\$ – Kamil Drakari Jan 29 '18 at 19:21
  • \$\begingroup\$ That'll be part of the API spec. Something like -1. \$\endgroup\$ – Nathan Merrill Jan 29 '18 at 19:31
  • \$\begingroup\$ This will probably be my last suggestion (for now): a link and/or description for "stable sort" will probably be helpful; I certainly needed to look it up, and is quite useful for informing strategies, as well as answering a question I otherwise had about handling ties. \$\endgroup\$ – Kamil Drakari Jan 29 '18 at 22:00

Efficient Tab Completion

Many tools that programmers use on a daily basis, like bash and Emacs, have tab completion.

  • Pressing Tab in certain situations will attempt to complete the text at the cursor, from a set of possibilities. The term is "completed" by filling in the remaining text.
  • For the aforementioned, if there are multiple candidates for completion, you will instead be shown a list of the candidates.
  • If there are multiple possibilities but they all start with the same substring/prefix, the rest of that substring will be filled in.

For example, to reach pydoc3, you only have to type


where Tab is shown as <TAB>. The tab key will insert oc, since all options starting with pyd also start with pydoc (in the set below).

a shot of bash tab completion options

The Challenge

Given a collection of strings called S and a target string called T, figure out the minimum number of keystrokes to reach T, assuming we're using tab completion and S is the set of possibilities.

  • Tab completion here is modeled after bash and Emacs, so it is case-sensitive.
  • The keystrokes/moves don't matter, only how many. A "keystroke" is:
    • Some character in the string
    • Tab
    • If S is [abc, ab] and T is ab, then either a<TAB> or ab will get there. Tab counts as one keystroke, so the method doesn't matter.
  • You may assume terms will only contain alphanumeric characters, underscore, and hyphen ([A-Za-z0-9]_-), for the purpose of this challenge.
  • You may assume no strings are empty.
  • You may assume S contains T (unsure about this one)
  • The input can be taken in whatever format is appropriate for your platform or language (array of strings, string with separators etc.) S and T are considered separate inputs.
    • I/O format is flexible and defaults apply (full program, function etc.)

This is , so shortest answer in bytes wins.

Test Cases

Set                                                 Target         Output
--------------------------------------------------  -------------  ------
[ab, abc]                                           ab             2
[lisp-mode, list-abbrevs, list-packages]            list-packages  5
[heck, hell, help_me, hello, goodbye, hello_world]  hello          5


  • Is anything vague or underspecified?
  • Is something too specific or cumbersome?
  • Is this too similar to an existing question?
  • Should we assume S will always contain T, or require a special case?
  • Should something be changed about case-sensitivity? Assume everything is lowercase?
  • Any tags I should use?
  • \$\begingroup\$ Hmm. wouldn't it be l<TAB>t-p<TAB> for #2? Also how to get hello in 4 keystrokes? \$\endgroup\$ – ASCII-only May 2 '18 at 0:48
  • \$\begingroup\$ You're right about list-packages, I'll fix it. And it looks like hello should be 5 keystrokes at hello. Good eye. \$\endgroup\$ – snail_ May 2 '18 at 0:55
  • \$\begingroup\$ You can get symbols for keys using <kbd> (<kbd>tab</kbd>) \$\endgroup\$ – 12Me21 May 2 '18 at 1:41
  • \$\begingroup\$ I like this challenge! A couple of questions: is it illegal to start typing with a TAB (could be useful when all the strings in S start with the same prefix)? Why is . not in the allowed characters, since it is present in your first example of pydoc? \$\endgroup\$ – Leo May 3 '18 at 1:15
  • \$\begingroup\$ You can use <TAB> wherever you want as long as it produces the minimum keystrokes. The image is supposed to be illustrative and not necessarily representative of the challenge itself; I worry that requiring too large or too specific a subset of characters will make the challenge more complicated than it needs to be (or maybe it won't affect much at all?) \$\endgroup\$ – snail_ May 3 '18 at 1:38
  • \$\begingroup\$ Assume S is [abcde] and T is abcdf. What should be the output? \$\endgroup\$ – user202729 May 4 '18 at 14:02

Existential Golf

  • \$\begingroup\$ Proofs could be simple: it supports NAND, and NAND is functionally complete. \$\endgroup\$ – tsh Jul 5 '18 at 7:23
  • 1
    \$\begingroup\$ @tsh Currently there is still no winning criteria. \$\endgroup\$ – user202729 Jul 5 '18 at 9:54
  • 3
    \$\begingroup\$ This is quite interesting (not sarcasm!), but what's the actual challenge? \$\endgroup\$ – Nathaniel Jul 7 '18 at 7:02
  • 3
    \$\begingroup\$ @Nathaniel When I actually finish it this will be the next installment of proof-golf. \$\endgroup\$ – Sriotchilism O'Zaic Jul 8 '18 at 3:19
  • 1
    \$\begingroup\$ It's great to see an unfinished idea, ready for feedback until it's postable. I see this as an important purpose of the sandbox. \$\endgroup\$ – trichoplax Jul 10 '18 at 19:43
  • \$\begingroup\$ @trichoplax Not everyone think so. \$\endgroup\$ – user202729 Jul 11 '18 at 3:46
  • 3
    \$\begingroup\$ I definitely disagree with having to make sandbox posts "finished". I agree with not being lazy though. I see this post as a great example of unlazy and unfinished (when posted). There was clearly effort made, and it was made available for feedback early, which can avoid going too far down a path that others already know won't work. Posting early prunes impossible or impractical challenges so challenge authors have more time for writing the challenges that will make it to main. \$\endgroup\$ – trichoplax Jul 12 '18 at 19:05
  • 1
    \$\begingroup\$ @user202729 For context, I said that in response to a 1-sentence sandbox post. I also said it bothers me when people "just post the bare minimum they can get by with and edit it later". The first revision of this challenge was clearly not the bare minimum to get by with. \$\endgroup\$ – DJMcMayhem Jul 12 '18 at 19:14
  • \$\begingroup\$ @DJMcMayhem So you're measuring effort? That's usually not a good idea. \$\endgroup\$ – user202729 Jul 13 '18 at 2:48

Split and recombine a number

This challenge has two related parts. Your task is to write two functions/programs as per the below specifications. You may share code across your submissions, the submissions may call one another, and you may even submit a single submission which handles both conversions. In the latter case, conversion direction may be determined by whether the input is a single number vs a list, or by an additional consistent second value (not a function) input.

Part 1

Given a floating point number, return a list with one element per digit of its integer part, if any, and if the number is a non-integer, one additional part which is the fractional part. If the number is negative, negate all elements in the output. If the number is zero, return a 1-element list with a zero in it.

When the result list is recombined as per Part 2, it must be precise to within an absolute or relative error of 10⁻¹⁰, whichever is more permissive.

Part 2

Given a list generated as per Part 1, return the number which would have generated that list in Part 1.

When the result number is split as per Part 1, each element must be precise to within an absolute or relative error of 10⁻¹⁰, whichever is more permissive.


Part 1 <-> Part 2
-123       [-1,-2,-3]
2.71828    [2,0.71828]
-800.6     [-8,0,0,-0.6]
321.7001   [3,2,1,0.7001]
-0.01      [-0.01]
100        [1,0,0]
0          [0]

  • \$\begingroup\$ (1) Technically infinities are floating point numbers (or, at least, they're not NaNs). What should the output be for an infinity? (2) How about for 1E45? (3) For numbers which are small enough to have a fractional part, what restrictions are there on the precision of the output? E.g. to take the fourth test case, 321.7001 - 321 in IEEE 754 double format gives 0.7001000000000204. \$\endgroup\$ – Peter Taylor Nov 18 '18 at 21:18
  • \$\begingroup\$ Do we need the leading 0 in the list? Seems cleaner without it \$\endgroup\$ – Quintec Nov 18 '18 at 22:11
  • \$\begingroup\$ @Quintec What leading zero? \$\endgroup\$ – Adám Nov 18 '18 at 22:28
  • \$\begingroup\$ @PeterTaylor I'll exclude infinities. I'm not sure what do do about inexactness. I guess I could allow stopping at 16 digits of precision. Any ideas? \$\endgroup\$ – Adám Nov 18 '18 at 22:31
  • \$\begingroup\$ Now that I think about it, string output for part one doesn’t make sense. But if it did, then I meant [2, .718] instead of [2, 0.718] \$\endgroup\$ – Quintec Nov 18 '18 at 22:43
  • \$\begingroup\$ I don't see any reason to reject 0 <-> [], given that 0.01 <-> [0.01]. \$\endgroup\$ – Bubbler Nov 19 '18 at 1:21
  • \$\begingroup\$ For the precision, how about something in the line of "correct up to absolute/relative precision of 1e-16"? Partly because big numbers stored in double are not accurate even in the integer parts. \$\endgroup\$ – Bubbler Nov 19 '18 at 1:29
  • \$\begingroup\$ @user202729 Yes, I'll add that. Also, see tolerance text now. \$\endgroup\$ – Adám Nov 19 '18 at 12:36
  • \$\begingroup\$ @Bubbler Tolerance specs added. \$\endgroup\$ – Adám Nov 19 '18 at 12:41
  • \$\begingroup\$ Suggested test cases: 4.4 <-> [4,0.4] and 44.44 <-> [4,4,0.44]. Also, can we assume there will not be any unnecessary trailing zeros? I have a working solution, even with workaround for 0 <-> [0], but for 0.0 it outputs [0.0], but vice-versa for [0.0] it outputs 0 instead of 0.0. Hence the question that there won't be test cases like 0.0, 4.0 or 6.4000 with unnecessary trailing zeros. My programming language outputs 4.0 -> [4,0] -> 40 due to the implicit conversion of 0.0 to 0.. \$\endgroup\$ – Kevin Cruijssen Dec 4 '18 at 10:44
  • \$\begingroup\$ @Adám FWIW Composed a solution using JavaScript for the specification at this question, and a solution for the specification at the original question (that currently has a bug for two test cases at "Part 2" portion, though is not incapable of being fixed). \$\endgroup\$ – guest271314 Dec 17 '18 at 23:47

Progress: Updated the rules again, and also add the timed function to the bots.

Sylver Coinage KotH

Sylver Coinage is a 2-player mathematical game that has the following rules:

  1. Two players take turns announcing a natural number each time.
  2. Each number announced must be unrepresentable as the sum of non-negative multiples of the numbers announced before.

    Eg. if the first three numbers announced are \$\{6, 11, 15\}\$, then you cannot announce any numbers representable as \$6n_1+11n_2+15n_3\$, where \$n_1,n_2,n_3\ge0\$. You can announce, for example, \$16\$, though.

  3. The player who announced a number not complying with Rule 2, or the number 1, loses.

Here is a twist -- R. L. Hutchings proved that announcing a prime number as the first play provides a winning strategy for the first player, although the detail of the strategy is not yet known. So I put a restriction here: the first player cannot announce a prime number in the first step. Now the first two numbers will be generated randomly by the driver at the beginning. No more restriction on prime numbers now.

Technical Information

A bot playing the game will have to implement a Python 3 class, extending TimedBot, with two methods: announce() and learn(). announce() should receive a list of numbers (possibly empty) and return a single integer, and learn() should receive two integers (id of the first move and second move) and the complete list of the numbers in the last game played.

Here is a sample implementation. Note: DO NOT use this as your submission -- this sample only serves as a demonstration, and it may announce numbers that violate Rule 2.

class SampleBot(TimedBot):     # must not be changed.
    def __init__(self, id):
        super().__init__()     # must not be changed.
        self.id = id

    def announce(self, list):
        import random
        return random.randint(1, 101)

    def learn(self, first, second, list):

Test Drive

class TimedBot:
    def __init__(self):
        self.time = 20.0

    def timed(func):
        def f(self, *args):
            import time
            a = time.time()
            b = func(self, *args)
            self.time -= (time.time() - a)
            return b
        return f

class SampleBot(TimedBot):
    def __init__(self, id):
        self.id = id

    def announce(self, list):
        import random
        return random.randint(1, 100001)

    def learn(self, first, second, list):

# very inefficient
def islinearcomb(n, l):
    if len(l):
        for i in range(0, n + 1, l[0]):
            if i == n:
                return [n // l[0]]
            elif len(l) > 1:
                isl = islinearcomb(n - i, l[1:])
                if isl:
                    return [i // l[0]] + isl
    return None

lose = -1
turn = 0
nums = []
bots = [SampleBot(0), SampleBot(1)] # replace with your bots here.

import random
while (len(nums) < 2):
    a, b, c, d = random.randint(1, 10), random.randint(1, 10), random.randint(1, 10), random.randint(1, 10)
    if 2**a * 3**b != 2**c * 3**d and 2**a * 3**b > 100000 and 2**c * 3**d > 100000 and 2**min(a,c) * 3**min(b,d) > 12:
        nums = [2**a * 3**b, 2**c * 3**d]
while lose < 0:
    v = bots[turn].announce(nums)
    print("{0}({1}) announced {2}".format(type(bots[turn]).__name__, bots[turn].id, v))
    w = islinearcomb(v, nums)
    if w:
        str = ""
        for i in range(0, len(nums)):
            if i:
                str += "+"
            str += "{0}*{1}".format(nums[i], w[i] if i < len(w) else 0)
        print("{0}({1}) announced {2} that is equal to {3}".format(type(bots[turn]).__name__, bots[turn].id, v, str))
        lose = turn
    elif v == 1:
        print("{0}({1}) announced 1".format(type(bots[turn]).__name__, bots[turn].id))
        lose = turn
    nums += [v]
    turn = 1 - turn
print("{0}({1}) wins".format(type(bots[1 - lose]).__name__, bots[1 - lose].id))


Each bot will have 20 seconds of time for deciding a move todo: adjustments. Running out time during the move results in a lose, and failing to finish a method within 20 seconds will lead to disqualification and rerun of all 100 rounds with the remaining bots.


Submissions will be open until todo: date here. After that 100 complete round-robin rounds will be done. Each pair of bots will compete twice in each round, one with the first bot announcing first, and one with the second bot announcing first. Each win brings 3 points, each draw brings 1 point, and each lose brings no points. The bot with the highest points after 100 rounds wins. The tiebreaker will be as follows:

  1. Points got
  2. Wins achieved
  3. Drawing lots
  • \$\begingroup\$ Probably needs some time limit for responses to prevent solutions which attempt to generate a full game tree. \$\endgroup\$ – Peter Taylor Dec 17 '18 at 9:26
  • \$\begingroup\$ @PeterTaylor Oh yes I thought about the time limit but I turned out forgetting to put that ;p \$\endgroup\$ – Shieru Asakoto Dec 17 '18 at 9:31
  • \$\begingroup\$ "The player who announced a number not complying with Rule 2 ... loses." I've been thinking about this. I presume that your intention is that the controller will validate the responses. An alternative would be to say that you don't automatically lose, but to add a type of response where the bot can return a proof that the opponent broke rule 2. Then bot programmers have to make a decision as to how much time to spend trying to show that their opponent lost vs computing a valid response. \$\endgroup\$ – Peter Taylor Dec 17 '18 at 20:48
  • \$\begingroup\$ What if a game goes on for a billion turns? \$\endgroup\$ – isaacg Dec 18 '18 at 1:13
  • \$\begingroup\$ @PeterTaylor I'd say my intention is that the controller will validate the responses. (in the test drive there is the code doing exactly that) \$\endgroup\$ – Shieru Asakoto Dec 18 '18 at 9:29
  • \$\begingroup\$ @isaacg If the number does not start out too large a game should end quite quickly. It is because two coprime numbers already make the number of possible moves finite. But If I pose a criteria on how large a number can at most go, then I'm feared that there may be a problem that the game tree is restricted. \$\endgroup\$ – Shieru Asakoto Dec 18 '18 at 9:30
  • \$\begingroup\$ I'd say: don't restrict the highest move, but give each bot a 'chess clock': they start with (say) 10s, and gain 1 second per move (and pass their clock's time as a parameter). Running over time is an automatic loss, and some percentage of time losses is a disqualification. Playing high moves will quickly exhaust their stock of time if they attempt to calculate extensive game trees, which will force the bots to either play quickly or lower their numbers. Adding a decay function to the time per move will encourage smart bots to play smaller numbers to not run out of time to think. \$\endgroup\$ – Spitemaster Dec 24 '18 at 16:47
  • \$\begingroup\$ @Spitemaster That's a good idea, but what I concerned about on large numbers is that the validation may take too long (because we are solving Diophantine equations in many unknowns) \$\endgroup\$ – Shieru Asakoto Dec 25 '18 at 5:48
  • \$\begingroup\$ Do you realise that guaranteeing that the first two numbers are coprime guarantees that the first player will win with correct play? If you want an interesting game then you should generate the first two numbers randomly as 3-smooth numbers with a GCD which is a multiple of 6 and greater than 12. \$\endgroup\$ – Peter Taylor Jan 9 at 11:16
  • \$\begingroup\$ @PeterTaylor Great catch! During discussion only the suggestion of giving two initial numbers was achieved, so I didn't realize that. \$\endgroup\$ – Shieru Asakoto Jan 10 at 0:39
  • \$\begingroup\$ I would remove the submission deadline, why not keep it open and update once a new entry comes? Also you might be interested in this (I adapted the code originally written for another KoTH), the easiest thing will be to enforce a certain formatting on the first line and adapt code_matcher to that formatting, st. that it won't break because everyone is using different formatting. \$\endgroup\$ – ბიმო Jan 10 at 13:48
  • \$\begingroup\$ @BMO Wow that's a good one! And I saw my code in the source lol BTW for the certain formatting part you mean the lines around class FooBar(TimedBot):? \$\endgroup\$ – Shieru Asakoto Jan 10 at 15:19
  • 1
    \$\begingroup\$ @ShieruAsakoto: Yeah, I added the header to bots.py which will be used, all the users' code will be appended to that and written to auto_bots.py.. Basically you'll only need to checkout the few variables (lines 12-20) and the main (from line 117) to see how it works. About the formatting, yes, that's probably the most sane: Make sure every code starts with class NameOfBot(TimedBot):, all definitions are in that class and it's valid Python 3 code (I updated the code_matcher like this it should work fine). \$\endgroup\$ – ბიმო Jan 10 at 15:33
  • \$\begingroup\$ If they/you use that bots.py you'll need to manually update the imports or do it inside the bot itself, atm. bots could use random and time, maybe add math too. \$\endgroup\$ – ბიმო Jan 10 at 15:34

Interleave Invariance

There is an infinite sequence that does not change when interleaved with the natural numbers. Consider these few terms:

1 1 2 1 3 2 4 1

Interleave them with the naturals:

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

As you can see, there is no change in the initial eight. Now, this sequence can be extended indefinitely rather easily by repeating this interleave operation. Your task is to choose and implement one of three output formats:

  1. Take as input a nonnegative integer n and output the nth term of this sequence, zero- or one-indexed (your choice).

  2. Take as input a nonnegative integer n and output the first n terms of this sequence.

  3. Output terms in order forever, starting from the beginning.

For options 2 and 3, there must be no numeric characters and at least one non-numeric character between terms; this separator need not be consistent. 1+1=2 would be fine for input 3. Leading and trailing non-numeric characters are allowed.

Here are the first 64 terms. This is OEIS sequence A003602.

1 1 2 1 3 2 4 1 5 3 6 2 7 4 8 1 9 5 10 3 11 6 12 2 13 7 14 4 15 8 16 1 17 9 18 5 19 10 20 3 21 11 22 6 23 12 24 2 25 13 26 7 27 14 28 4 29 15 30 8 31 16 32 1

Your submission can be a program or a function; "input" and "output" are as defined by the community. Standard loopholes are forbidden.

As this is , the shortest solution (in bytes) wins! Good luck, and happy golfing!

Sandboxy Stuff

Am I clear enough on what the sequence is? Any suggestions for rewording?

Is this a duplicate? I've searched for "interleave" and "3602" and found nothing.

Anything else worth mentioning? What thoughts ya gots?

Thanks to Martin Ender for the output formats, taken almost straight from the Kolakoski challenge.

  • 1
    \$\begingroup\$ related (not a dupe though) \$\endgroup\$ – dzaima Feb 13 at 19:35
  • \$\begingroup\$ You could consider removing the option to output just the n'th term, making answers output a sequence. Otherwise I think it will be shortest in most languages to take n, halve until non-whole, then add 1/2 (ceiling), rather than use the interleaving property which I think is cooler. \$\endgroup\$ – xnor Feb 15 at 0:46
  • \$\begingroup\$ It looks like n/(n&-n)/2+1 would work for a lot of languages such as Python. \$\endgroup\$ – xnor Feb 15 at 1:09
  • \$\begingroup\$ @xnor Do you think removing that option will help much? I can't really think of a case where the solution won't be to wrap your expression in a looping construct if the expression was the shortest. I don't think knowing the history of this function is that helpful to finding the future value. \$\endgroup\$ – FryAmTheEggman Feb 25 at 22:09
  • \$\begingroup\$ @FryAmTheEggman You're probably right, answers would mostly just do the expression in some loop. In Haskell I think the interleaving definition wins out (even with option 1 allowed), but maybe that's just Haskell. \$\endgroup\$ – xnor Feb 26 at 6:22

Is this checkmate?


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


Two distinct consistent outputs for checkmate or not.


enter image description here

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

  • \$\begingroup\$ I suggest wording similar to “two distinct consistent outputs for checkmate or not” \$\endgroup\$ – Quintec Mar 12 at 11:52
  • \$\begingroup\$ @Quintec Thanks. \$\endgroup\$ – Anush Mar 12 at 11:58
  • 4
    \$\begingroup\$ I'd recommend keeping it all self-contained and having a description for the FFN format, as well as a few more test cases \$\endgroup\$ – Jo King Mar 12 at 21:41
  • 2
    \$\begingroup\$ Is restricted to the FFN format a part of the challenge? Why not allow it in any reasonable format? \$\endgroup\$ – tsh Mar 13 at 5:47
  • \$\begingroup\$ @Quintec why not just say truthy or falsey? \$\endgroup\$ – qwr Jun 20 at 14:48

Evaluate C−− expression

Your goal is to a evaluate an expression in "C−−" (not this one) which uses only the characters are C and -. C is an variable holding an integer whose initial value you're given, and the - symbol is used in many ways including as a decrement operator:

  • C-- decrements the value stored in C, then evaluates to that value.
  • --C evaluates to C, then decrements the value stored in C.
  • -expr negates the value of the expression expr.
  • expr1-expr2 takes the difference of the two expressions.

Unfortunately, the C−− specification doesn't state how expressions are parsed or in what order parts are evaluated, saying these are "implementation dependent". So, it's up to you. For example, --C---C could be interpreted as -(-(C--)-C) or (--C)-(--C) or others, and each --C might be evaluated before or after other parts of the expression.

Input: A string consisting of C and -, and an integer initial value for C.

The string will be parseable in at least one way. You can take the string as a list of characters, but they must be exactly the characters C and -.

Output: A value this expression could evaluate to.

You don't need to worry about issues with overly large values like overflows or loss of precision.

TODO: test cases

  • 2
    \$\begingroup\$ Can --C---C be parsed as -(-(C-(-(-C))))? \$\endgroup\$ – H.PWiz Apr 13 at 17:44
  • 2
    \$\begingroup\$ @H.PWiz Yes. Unfortunately, it looks like as is --C, can always be interpreted as -(-C), which is golfier but more boring, so I'll probably restrict the parsing or removing the unary negation option. \$\endgroup\$ – xnor Apr 13 at 17:50
  • 1
    \$\begingroup\$ @xnor Note: -C is the same as (C-C)-C, but there are no parentheses here so nobody can say it can't also be parsed as C-(C-C). An added rule can be "You can't parse --C as -(-C), as a double negation would be meaningless." \$\endgroup\$ – Erik the Outgolfer Apr 13 at 17:55
  • \$\begingroup\$ Do you want to include or exclude simple eval implementations? \$\endgroup\$ – Phil H Apr 29 at 15:22
  • \$\begingroup\$ @PhilH That's a good question. Eval-style solutions seems pretty boring for C-style languages, but I don't know if there's a clean way to even specify what would be disallowed. I don't have time to work on this challenge, so you're welcome to spruce it up and post it if you want. \$\endgroup\$ – xnor Apr 30 at 1:05
  • \$\begingroup\$ if the C-- in question is not the one linked, could you link the one you're referring to? You mentioned a C-- specification, so I assume there is one \$\endgroup\$ – Skidsdev May 3 at 17:29
  • \$\begingroup\$ @Skidsdev I meant it as a thing I'm making up for the challenge. \$\endgroup\$ – xnor May 3 at 22:02

An Auction in St. Petersburg


Mysterious packages are up for auction today. These boxes are unique in that their values are not known until they are opened, and when they are opened, their values follow a unique distribution:

probability    value
0.5               $2
0.25              $4
0.125             $8
0.0625           $16
1/(2^n)       $(2^n)

In total, there are 100 such packages up for auction, to be sold sequentially. At the start, each bot arrives with $20 in their wallet, and the goal is to walk away with more money than anyone else.

During each round in the auction, each bot simultaneously submits a bid. The bot with the highest bid (ties broken randomly) must pay the value of the second-highest bid, after which that winning bot receives an amount of money corresponding to the value of the opened package. This money can then be "reinvested" in future rounds of the auction.

The auction day ends once all 100 packages have been sold, or when any bot's wallet value exceeds 2^31.

I/O format

As input, your bot receives the following info:

  • an array of everyone's current wallet amounts
  • the history of past sale prices (the amount paid, not highest amount bid) and winners

As output, your bot returns an integer between 0 and your current wallet amount.

Tournament format

There will be N=large number of game run according to the above format (100 auction rounds each), and the finishing position of the bots will be averaged across games.

  • \$\begingroup\$ Could you explain why it ends when someone reaches 2^31? \$\endgroup\$ – Artemis Fowl Apr 16 at 3:17
  • \$\begingroup\$ @ArtemisFowl It's mostly to prevent players from having to deal with numbers that don't fit into a 32-bit integer. There's only a 1 in 1 billion chance that a particular package will contain enough money to trigger this condition, I just wanted to clarify how I would handle the "infinite expected value" in practice. \$\endgroup\$ – PhiNotPi Apr 16 at 14:45
  • 1
    \$\begingroup\$ This seems rather win-more. It just takes one big win to be able to guarantee that you can outbid everyone else for the rest of the game. \$\endgroup\$ – Peter Taylor Apr 20 at 21:40

Complete the grid-filling meander

A grid-filling meander is a closed path that visits every cell of a square 𝑁×𝑁 grid at least once, never crossing any edge between adjacent cells more than once and never crossing itself. For example:

Once filled, each cell of the grid can be represented by one of the following 8 tiles:

Numbered this way, the tiles of the above meander can be represented by this matrix:

5 6 5 6
4 8 3 2
5 7 6 2
4 3 4 3

Your task is to complete a grid-filling meander given an incomplete set of tiles. For example, the incomplete meander:

...which can be represented using 0s for missing tiles:

5 0 0 0 6
0 0 7 0 0
0 0 0 0 3
2 4 0 0 0
0 0 3 0 0

...could be completed like this:


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


  • The input will always have at least 1 and at most 𝑁2 (non-empty) tiles, where 2 ≤ 𝑁 ≤ 7.
  • You may use any set of values to represent the tiles, as long as it's specified in your answer.
  • Your input and output may be in any format and order, as long as it's specified in your answer.
  • At least one valid solution will exist for all inputs (i.e. you don't need to handle invalid input).
  • Standard I/O rules apply.
  • Standard loopholes are forbidden.
  • Explanations, even for "practical" languages, are encouraged.

Test cases

Input (Θ):

0 6
0 0

Output (Θ):

5 6
4 3

Input (Θ):

5 6 5 6
4 0 3 2
5 7 6 2
4 3 4 3

Output (Θ):

5 6 5 6
4 8 3 2
5 7 6 2
4 3 4 3

Input (Θ):

5 0 0 0 6
0 0 7 0 0
0 0 0 0 3
2 4 0 0 0
0 0 3 0 0

Output (Θ):

5 6 5 1 6
4 8 7 6 2
5 7 7 7 3
2 4 8 8 6
4 1 3 4 3
  • \$\begingroup\$ A meander is not just any arrangement of those 8 tiles, it has to be one where the edges match. \$\endgroup\$ – Sriotchilism O'Zaic yesterday
  • \$\begingroup\$ @SriotchilismO'Zaic Is that not made clear by the first sentence? Please let me know if you can suggest a clearer way to phrase it. Thanks! \$\endgroup\$ – Jordan yesterday
  • \$\begingroup\$ That's not quite what I meant, the first sentence describes one way to think about meanders, and then you say "We can also think of this as an arrangement of the following 8 tiles" which is not quite true since the edges have to match in order for these two to be the same. You might want to say "We can also think of this as an arrangement of the following 8 tiles where the edges match." Or something like that, so that the two are the same. \$\endgroup\$ – Sriotchilism O'Zaic yesterday
  • \$\begingroup\$ @SriotchilismO'Zaic I see. "This" in that sentence was meant to refer to the preceding image, not the concept of meanders, but you're right that it wasn't clear. I've tweaked the wording a bit but may revisit it again. Thanks for your input. \$\endgroup\$ – Jordan yesterday

BlackJack Part II

Repost from the original sandbox

As I had a blast working on the original KOTH challenge, I wanted to come up with another. For me, the fun of these AI challenges is in refining a comparatively simple bot which plays a very simple game subtly. Due to the probabilistic nature of card games, I think that blackjack could be an interesting KOTH game just like TPD.


  • Bots play at tables of four (4) competitors and one (1) dealer
  • One (1) shoe is shared by all players and the dealer until it is exhausted, at which point a new randomly shuffled deck will be added and play will continue. The bots ARE NOT (at present) NOTIFIED of the addition of this new deck. [TODO? would make card-counting a LOT harder...]
  • There is a buy-in of 10 per round, and cards are free
  • There is no bet maximum as bets are between the player and the house, yet the bot must have sufficient chips to immediately finance the bet.
  • Perfect/ideal hand has a score of 21
  • All face cards have a value of 10
  • All numeric cards are worth their number
  • Aces are worth 11 or 1. this will be dealt with automatically by the framework, not the bots.
  • Scores in excess of 21 which use an ace as 11 force the ace to reduce in value to 1 scores in excess of 21 which cannot be coerced below the threshold of 21 "bust" the bot
  • The dealer draws until he busts, or excedes a score of 17.
  • The stake is subtracted from chips, so the chips value is the number of credits which are available to the bot for betting.

Dealing and Bot Moves

  1. When the game starts, each player is iteratively dealt one card, and has the $10 buy-in fee/minimum bet subtracted from their chips.
  2. Then (in the same order as they were dealt to) each bot is executed as described in the "Programmer's Interface" section and must make a move or stand. Betting is considered a move. NOTE THAT BETTING DOES NOT AFFECT BOTS' ABILITY TO MAKE FURTHER MOVES. It is very possible to bet and then draw a card, and it is possible to draw multiple cards and them bet before standing.

Programmer's Interface and Legal Moves

As documented in the CardShark class:

#          $ ./foo.bar <hand-score> <hand> <visible cards> <stake> <chips>
#          <hand-score>     is the present integer value of the player's hand.
#          <hand>           is a space-free string of the characters [1-9],A,J,Q,K
#          <visible cards>  every dealt card on the table. when new shoes are brought
#                           into play, cards drawn therefrom are simply added to this list
#                           !!! THE LIST IS CLEARED AT THE END OF HANDS, NOT SHOES !!!
#          <stake>          the  number of chips which the bot has bet this hand
#          <chips>          the number of chips which the bot has
#          $ ./foo.bar 21 KJA KQKJA3592A 25 145
#          "H"|"S"|"D"|"B"  (no quotes in output)
#          "H"              HIT - deal a card
#          "S"              STAND - the dealer's turn
#          "D"              DOUBLEDOWN - double the bet, take one card. FIRST MOVE ONLY
#          "B 15"           BET - raises the bot's stakes by $15.

Winner Selection

The winner would be the author of the bot which consistently accrued the most chips over a yet-to-be determined number of tables and rounds.

Code Review github

Issues & ToDo

None! (no known problems at least)

PS. How do I tag questions/answers? thanks @dmckee [ai-player] [card-game] [koth]

Version History

5/25 - 0020 - v1 - updated code on GitHub which fixes a bug with the dealer. DD still scores monstrously for unknown reasons. tagged this post (with any luck).

5/25 - 0800 - v2 - bugfix on github which correctly implements DoubleDown, resulting in drastically reduced scores from the double-nut bot.

5/25 - 0920 - v3 - updated the test case to match the input specification. Added the rules for the dealer.

5/25 - 1100 - v4 - added a description of the table and shoe system.

5/25 - 1620 - v5 - added an explanation of the betting and card-dealing system, major status update.

5/27 - 1700 - v6 - ready to roll the contest...

  • 1
    \$\begingroup\$ Tags: [ai-player] and [card-game] seem naturals, though neither exists on the site as yet. What else? \$\endgroup\$ – dmckee May 25 '11 at 4:00
  • 1
    \$\begingroup\$ The SAMPLE INPUT isn't consistent with the INPUT SPECIFICATION - do the args include the current score or not? How many decks of cards should we assume to be used? Does <chips> include <stake>? How does the AI dealer play? Is each bot-dealer pair using a separate shoe (so that when I stand the dealers cards are drawn fairly from all those not included in <hand> and <visible-cards>)? When does betting occur? \$\endgroup\$ – Peter Taylor May 25 '11 at 12:17
  • \$\begingroup\$ should players be notified of the number of decks in play, or not? The issue is that decks are dealt from until the deck is exhausted, then the "cannot pop from empty list" error signals the creation of a new shuffled deck then continues drawing as if nothing had happened. This means that multiple decks can be in play at once, but the statistical worst-case is that each player has three or four cards, which makes between fifteen and twenty samples split between two decks of 52. It shouldn't make a difference to score-based bots, but card-counters will need to detect or be notified of the chage \$\endgroup\$ – arrdem May 25 '11 at 15:16
  • \$\begingroup\$ Can we delete this because the sandbox lags so much and this hasn't been touched in 6 years? \$\endgroup\$ – programmer5000 Apr 13 '17 at 17:29

Given a text, determine the language it is written in. The possible languages are: English, Danish, Romanian and Hungarian. The shortest program wins.

Some examples of text in each language can be found at Project Gutenberg

You are required to include examples of runs on text files other than the ones provided here.

The input file name is given as a command line argument. Except the input text, you are not allowed read additional files (e.g. to train your program) so please encode any data in your program.

Your program must output on of the following words English, Danish, Romanian, Hungarian.


$ ./language pg2600.txt
$ ./langauge pg12167.txt
$ ./language 11756-0.txt
$ ./language 30163-0.txt
  • \$\begingroup\$ Another source of plain text passages might be the Gutenburg project. They do have books in languages other than English. \$\endgroup\$ – dmckee Jun 22 '11 at 14:53
  • \$\begingroup\$ Thanks. I updated the text problem to include some books from Gutenberg. \$\endgroup\$ – Alexandru Jun 22 '11 at 15:04
  • \$\begingroup\$ Related \$\endgroup\$ – Beta Decay Sep 7 '16 at 10:32
  • \$\begingroup\$ Looks pretty trivial to me. Any sufficiently long text will have ă if Romanian, ő if Hungarian, å if Danish, and neither if English. None of the special characters occur in any other of the four languages. \$\endgroup\$ – Adám Jun 5 '17 at 10:45
  • \$\begingroup\$ Hello! This looks like a good but abandoned meta post, would you be willing to offer it for adoption? (If you want to, you can still post to main.) \$\endgroup\$ – programmer5000 Jun 9 '17 at 15:20
  • \$\begingroup\$ @programmer5000 The OP hasn't been seen since 2011, I think you're fine. \$\endgroup\$ – TheLethalCoder Jul 21 '17 at 13:21

How long until my next birthday is on a weekend

I would like to know how much time (in days) I have to wait (from now) until my birthday occurs on a weekend...

  • The required tool could accept arguments or standard input.
  • The only variable passed as input (as argument or stdin) is my birth day in the strict form YYYY/MM/DD with only digits, separated by / (of course: YYYY for birth year, MM for the month and DD for the day of month.
  • The output must present the number of days to wait, from now, and the target date with the day of week, in the form Wait DTW days to WWW, YYYY/MM/DD where DTW in integer is the number of days to wait, WWW as day of week abbreviation could be Sat or Sun and the target date in same form as input.
  • Once done, there is no more request (tool could finish quietly, loop, bug or crash)
  • About February 29th, there are 3 ways you can handle it:

    • strict: Where birthday may occur once every 4 years
    • right: Where birthday is March 1st while Feb 29th doesn't exist.
    • relax: Where birthday could be Feb 28th or March 1st, but only while Feb 29th doesn't exist.

    The tool must match in the right manner, but could accept an option as choice between one of the three ways.

  • Shortest golfed code wins
    • -3 explanation (while golfed version must use one letter variable, ungolfed version is welcome with useful variable names)
    • -3 if properly loop on STDIN
    • -5 if no requirement of external library
    • -10 if an option to choose the way of considering February 29th.
    • 0 for shebang (unless they contain more than runtime options: switch r in sed or p in perl are runtime options, they count for null)
    • N embed code on shebang line in counted normally.
  • 2
    \$\begingroup\$ How would you handle birthdays on February 29th? It would be an interesting special case, and it will increase the complexity of the problem. \$\endgroup\$ – PhiNotPi Dec 13 '13 at 23:15
  • 1
    \$\begingroup\$ Is this going to get answers which are much different to the currently active calendar-related questions? IMO it would be best left for a couple of months. Variety is a good thing. \$\endgroup\$ – Peter Taylor Dec 13 '13 at 23:41
  • \$\begingroup\$ @PeterTaylor I'm not sure about what to answer to this. I think: yes in that: there is two input: current day and birthday, a range in week, not only one day and may different thinking may build different solution... \$\endgroup\$ – F. Hauri Dec 14 '13 at 9:34
  • \$\begingroup\$ @PhiNotPi Thanks, question edited! \$\endgroup\$ – F. Hauri Dec 14 '13 at 9:42
  • \$\begingroup\$ @PeterTaylor I've already browsed calendar questions ;-) \$\endgroup\$ – F. Hauri Dec 14 '13 at 9:46
  • \$\begingroup\$ Instead of listing this as code-golf, I recommend that you list it as code-challenge and change "Shortest golfed code" to "Lowest score" and add: 1 for each char \$\endgroup\$ – Justin Dec 21 '13 at 7:35
  • \$\begingroup\$ This sandbox post has had little activity in a while. Please improve / edit it or delete it to help us clean up the sandbox. Due to community guidelines, if you don't respond to this comment in 7 days I have permission to vote to delete this. \$\endgroup\$ – programmer5000 Jun 9 '17 at 15:39

3D Maze Navigation

Output a path through a 3D maze.


The input will be from STDIN and will be a 3D maze. The maze will be input in slices horizontally across the maze starting from the top and moving down to the bottom. Each slice will be of the same width and depth, though the width, depth and number of slices could be different from run to run, and each slice will be separated by a blank line in the input. Here's an example:


*@* *
* * *
*   *

*** *

*>* *
* * *
*   *


The * character represents a solid wall or floor, @ is our hero and > is the exit from the maze.


The aim is to find if there is a way for the hero to get to the exit, and if there is, to show him the way with a series of directions:


Obviously this is a very simple maze, but the test cases will be harder than this. To complicate matters, the maze includes zero or more doors which can only be opened if the hero has picked up the correct key on the way. Each key is represented by a lower case character, and will only open a door represented by the uppercase version of the same letter (so a opens door A, b opens B and so on). The action of picking up a key is represented in the output with an X, and the hero has small hands and so can only hold one key at a time (his other hand is holding his mobile phone so he can keep track of his SO reputation). This may mean in some cases that he has to backtrack to get the next key required.

A couple of examples:



* *D*
*d  *




The key and door have to be in the correct order, he can't use a key from beyond the door to open the door. If the maze has no solution, you should output nothing at all.



* *d*
*D  *



I'm providing a few test cases.

Test case 1


******                ******
******                ******
******                ******
******                ******
******                ******
******                ******
******                ******
******                ******
******                ******
******                ******

******                ******
** * *                *    *
** b**                * ** *
** * *                * *  *
*  * *                * ****
* ** *                * *> *
*    *                * ** *
***A**                * ** *
*@   *                * *  *
******                ******

** * ***********************
**** ******************** **
**** ****************** ** *

** * *        *    **   *  *
** * * ****** * ** *  * * **
* B* *   *    * e* * ****  *
* **** * *c***** *   *   * *
*  **  * *    ** ***** **  *
**    ** ****  *        * **
*  *****C*** ** * *****E* **
*d**a***D             * *  *


Output (other solutions may exist, but I think this is the shortest)

  • \$\begingroup\$ If W puts out F and K opens D, who specifies that? Maybe you could go abstract and say that A unlocks a, B unlocks b... \$\endgroup\$ – John Dvorak Dec 23 '13 at 13:09
  • \$\begingroup\$ @JanDvorak The pairs of obstacles and equipment need to overcome them would be specified in the question. At the moment I'm trying to see if that's a complication too far and if I should stick to the easy version of the challenge (I think I'd prefer to post the harder version, but there's no point if no-one would answer it). \$\endgroup\$ – Gareth Dec 23 '13 at 14:08
  • \$\begingroup\$ I don't mind keys and doors (somehow I like the extra challenge), but memorizing a {char x char} lookup table doesn't really serve anything. \$\endgroup\$ – John Dvorak Dec 23 '13 at 14:10
  • \$\begingroup\$ @JanDvorak Okay, that's a fair point. \$\endgroup\$ – Gareth Dec 23 '13 at 14:11
  • 1
    \$\begingroup\$ On that same note, I suggest using non-alphanumerics for the hero and exit. You can get inspired by the rougelike genre: @ means the hero, and > means "stairs down" (exit). Or, you could use < (stairs up) for the starting point. Then the path/non-path would be dots (lit floor) vs. spaces (unlit floor). \$\endgroup\$ – John Dvorak Dec 23 '13 at 14:15
  • \$\begingroup\$ Is the solid border guaranteed? \$\endgroup\$ – John Dvorak Dec 23 '13 at 16:42
  • \$\begingroup\$ Yes. There will be a a solid border to each side and above and below. There will be no way to escape the maze in any of the test cases. \$\endgroup\$ – Gareth Dec 23 '13 at 16:43
  • \$\begingroup\$ Also, what if there are multiple paths? Which path should we choose? \$\endgroup\$ – John Dvorak Dec 23 '13 at 16:44
  • \$\begingroup\$ For the purposes of providing test scripts, I'd probably ensure that there was only one possible path in the tests. Maybe I should add a guarantee that that would be the case in the question? \$\endgroup\$ – Gareth Dec 23 '13 at 16:51
  • \$\begingroup\$ Without the keys this is just another shortest path question, so I think the keys are essential to make it interesting. However, they potentially lead to routes which double back on themselves, and the output format doesn't handle this well. What do you think to changing the output to a string of e.g. NSEWUD? \$\endgroup\$ – Peter Taylor Dec 24 '13 at 7:58
  • \$\begingroup\$ @PeterTaylor I thought the 3D aspect might make it more interesting than another shortest path question? Yes, I'm very flexible on the output format. My biggest worry is making the test cases such that there is only one possible correct answer to make it easy for me to modify the test scripts that I already use. \$\endgroup\$ – Gareth Dec 24 '13 at 10:14
  • \$\begingroup\$ 3d changes the lattice structure slightly but IMO it's a trivial change. The keys add a dimension each. To help the unique solutions you could prohibit doubling back, so that each step adds a dimension and steering AI is necessary to keep performance acceptable. \$\endgroup\$ – Peter Taylor Dec 28 '13 at 10:08
  • \$\begingroup\$ @PeterTaylor Is it better to prohibit doubling back or maybe only allow the holding of one key at a time (requiring doubling back to get the correct key in some cases)? \$\endgroup\$ – Gareth Dec 30 '13 at 22:52
  • \$\begingroup\$ Holding one key at a time increases the state space moderately (I make it a factor of n * 2^n), but I expect answers would still be straight Dijkstra. It adds a complication which should be clarified: if I'm carrying a key, am I prohibited from stepping on a different key, or do I pass over it and leave it alone? \$\endgroup\$ – Peter Taylor Dec 31 '13 at 8:33
  • \$\begingroup\$ @PeterTaylor If I was to take that path you would be able to pass over keys without picking them up. \$\endgroup\$ – Gareth Dec 31 '13 at 9:46

4 and 20 baked in a π

While some might describe π as a string of seemingly random numbers, one can also look at it in a way similar to a monkey with a typewriter. Eventually, it should calculate out to something more interesting. For example, the sequence 1337 shows up 4,814 places to the right of the decimal. At 700,731 places right of the decimal, you'll find the sequence 160151, which is "pi" represented as ASCII (although you'll find a 'pointer' to it much faster, as the sequence 700731 begins at 29,830 digits to the right).

So, your task is to make a program to find things in π. Your program will accept a positive integer and output the number of places right of the decimal point that number appears. To keep the run times down, input can be limited to numbers in the range of 0 to 1000 (without leading zeros).

Example: Using 415 as the input, the output should be 2:



  • You can not use any precalculated values of π, including language constants, built in functions that return π or digits of π, or any resource outside the code itself (such as files or websites).
  • You can not use any trig functions to calculate π.

Bonus points if you find the sequence 072 101 108 108 111 044 032 087 111 114 108 100 033.

This is code golf, so lowest score wins.

  • 1
    \$\begingroup\$ It's not clear to me whether you require answers to support leading zeroes. Also: program, named function or snippet? And how indexed? (Giving 415 as a test case would be a good way to answer the last question) \$\endgroup\$ – Peter Taylor Mar 11 '14 at 6:58
  • 3
    \$\begingroup\$ Isn't this just Calculate 500 digits of pi with a search function tagged on at the end? By the way, your bonus points are quite safe — even if you searched a trillion trillion trillion digits of pi, your chance of finding an arbitrary 39-digit sequence would still be less than 0.1%. \$\endgroup\$ – squeamish ossifrage Mar 11 '14 at 14:59
  • \$\begingroup\$ Edited to clarify leading zeros and indexing. @squeamishossifrage - Yes and no. The number of digits to find the answer depends on the input, which both limits the choice of algorithm to generate the search space and gives more ample room to golf the integration of the search function. The worst case is under 10000 digits for n between 0 and 1000. I suppose I could put in a time limit of a couple minutes and expand the range of n to 10000 (worst case is just under 390k), but that seems obnoxious. Thoughts? \$\endgroup\$ – Comintern Mar 11 '14 at 17:20
  • 1
    \$\begingroup\$ @AlexA. - Not a drug reference. \$\endgroup\$ – Comintern Apr 1 '15 at 22:34
  • \$\begingroup\$ Hello! This looks like a good but abandoned meta post, would you be willing to offer it for adoption? (If you want to, you can still post to main.) Due to community guidelines, if you don't respond to this comment in 7 days I have permission to adopt this. \$\endgroup\$ – programmer5000 Jun 9 '17 at 16:15

Save your job in QA!

You work for a software company's QA department, writing automated acceptance tests for their products. One day, your boss calls you in to his office, and to your astonishment tells you that your entire department is being "rationalized".

"But why?" You ask

"One of the fellows in development told me about these new-fangled things called 'unit tests'. Apparently, you can test each little bit of code as you write it. And since the developers do it themselves, that means we don't need a QA department any more."

You hesitate. "Well unit tests are a good idea, but you still need-"

"Nonsense!" Your boss blusters, cutting you off mid-sentence "If we can test every little bit of the code, we don't need to test the whole lot again!"

Your boss is adamant, but after a bit of wrangling, he grants you one chance: later that day, you will present him with a demonstration proving that unit tests alone aren't enough to test your product.

The challenge

Your challenge is to write the following:

  • A system under test with more than one part
  • Unit tests for each part
  • One or more integration tests, consisting of multiple parts working together

The unit tests should appear to prove that the system under has one behaviour, while the integration tests should prove that it actually has another.


This is a popularity contest, and the following criteria should be taken into account for rating the answers:

  • The trick leading to the unit tests having different conclusions to the integration tests should be primarily in the system under test. Your boss won't be impressed if all you did was insert a bug into one of your tests!
  • The more convincingly the individual unit tests and integration tests appear to prove what they are each attempting to test, the better.
  • The more convincingly the conclusions of the integration tests appear to contradict the unit tests, the better. For example, an answer where both the unit tests and integration tests use the same inputs to the system under test would probably be better than one that relies on them using different inputs. An answer where the integration test tests some behaviour of the system which was clearly not covered by the unit tests would also not be a very good answer.

Tests may be written in whatever format is appropriate for the language you are using. Two possibilities which would work in many situations would be:

  • Tests have no return value, but throw an exception (or equivalent) if they fail
  • Tests return true for a pass or false for a fail

Cube puzzle

Write a program that can determine whether or not a collection of puzzle pieces can be assembled to form a solid cube. The pieces can be moved and rotated, but not reflected.

Each puzzle piece consists of a connected set of sub-cubes. The arrangement of these sub-cubes is described an ASCII representation consisting of a single line with three space-separated numbers x, y and z, followed by z blocks of x × y characters where X represents an occupied sub-cube, and . represents an empty sub-cube. The first line of input indicates the number of puzzle pieces that follow (N).


Your program should accept input from stdin, and should print its results to stdout. If the pieces can form a cube, it should output the line "CUBE". If not, it should output "NOT A CUBE".


enter image description here

In the above illustration, a 3×3×3 cube is constructed from five pieces. If the pieces are listed in the order {pink, yellow, blue, red, green}, then the input could look something like this:

3 2 1
3 2 2
3 3 2
2 3 1
3 3 2


Your program should be able to handle any puzzle comprising up to 10×10×10 sub-cubes.

Winning criterion:

This is a challenge. The shortest answer (measured in bytes of code) will win.

  • \$\begingroup\$ This is a nice idea but the input format seems complicated. I have another idea: use directions to define the pieces. For example for the pink piece: .RRU (start, then go to Right twice then go to Up). Directions are Up, Right, Dowm, Left, Front and Back. \$\endgroup\$ – A.L Jun 25 '14 at 21:42
  • \$\begingroup\$ OK, but how would that work for pieces that contain branches (like the blue one, for example)? \$\endgroup\$ – squeamish ossifrage Jun 26 '14 at 14:37
  • \$\begingroup\$ Ah, I forgot this case. :-) I think we can use a direction to get back from the branch to the trunk. For example for the blue one: .RTTBFTLRR (the point is view is located at the left of your image) \$\endgroup\$ – A.L Jun 27 '14 at 2:44
  • 1
    \$\begingroup\$ @A.L what does T signify? \$\endgroup\$ – trichoplax Jul 19 '14 at 21:21
  • \$\begingroup\$ @githubphagocyte oops, I wrote T for Top, it's U instead. \$\endgroup\$ – A.L Jul 19 '14 at 23:06
  • 1
    \$\begingroup\$ @A.L so .RUUBFULRR? Makes sense now thank you. \$\endgroup\$ – trichoplax Jul 19 '14 at 23:22
  • 1
    \$\begingroup\$ Hello! This looks like a good but abandoned meta post, would you be willing to offer it for adoption? (If you want to, you can still post to main.) Due to community guidelines, if you don't respond to this comment in 7 days I have permission to adopt this. \$\endgroup\$ – programmer5000 Jun 9 '17 at 16:53
  • \$\begingroup\$ @programmer5000 You're welcome :-) \$\endgroup\$ – squeamish ossifrage Jun 10 '17 at 21:41

Paired Programming: Down Periscope!

This is very basic for now, and lacks specific numbers as I flesh out the details and play with the speeds involved. I/O will be pretty basic, but it's not fully outlined yet.

Four submarines are placed in an arena, two on each team. They shoot torpedoes at each other. The objective, as obvious as it seems, it to kill the opposing team.

Teams are made from all pairwise matches of entries. They are then placed in a tournament-style bracket, deep enough to fit all of them. Any empty spaces are filled with a team of two dummy submarines, effectively creating a bye assuming you don't lose to a team that quite literally can't kill you.

The tournament is played several (many?) times to tally points. The team with the most points at the end is the winning team. In the interests of selecting a single winner, the winning team's bots will be compared. Whoever got the most points total (even from their participation on other teams) is the overall winner. Note that this means the single bot with the most points may not win (due to not being on the winning team).

Sensors down, Captain

Unfortunately, you've lost most of your communications ability, and your navigation sensors are limited. Specifically, you have two ways to figure out what's around you and/or communicate: passive and active.

  • Passive Audio: Since water is such a great conductor of sound, you can hear things from a pretty good distance. Of course, today's submarines can run pretty quietly, but as they speed up, they get louder. You can also hear other things, like active torpedoes, explosions, and sonar pings. For each of these events, you will receive a bearing (azimuth/elevation) and a loudness. Loudness drops off with distance, so you may not be able to hear everything in the arena. You don't have to directly ask for this information, it will be supplied on each turn.

  • Active Sonar: When that just isn't good enough, there's sonar. When you activate a sonar ping, you will receive a bearing and distance to all objects (submarines/torpedoes). Of course, other subs will also be able to hear you when you do.

(Tentative) As a bonus, you can modulate a short message onto the sonar ping to communicate with other subs. This message can be up to 16 bytes in length. Just remember, all other subs will be able to hear this message, not just your teammate. They will hear it as an addition to the ping during passive listening. If you have idea about how to make this useful/effective, I'm usually available in chat.

Take us down

Movement is based on vectors, and any movement commands you give are applied. Acceleration is a fcator in speed and direction, so you can't go from full stop to all out in one step. To move, you need three values: left/right, up/down, and throttle.

  • Left/Right: Supplied in absolute degrees from north. There is a maximum turn rate, so the ship will slowly come about to face the new heading. If the value is out of the bounds 0<=d<=359 it will be modulus 360. The ship will turn in whichever direction would result in the shorter turn, so if you want to make a 270-degree clockwise turn from north, you'll need to do it in increments of something <= 180. If you set a heading exactly 180 degrees from current, it will turn clockwise.

  • Up/Down: Supplied in absolute degrees of the desired angle. The ship will slowly come to the desired angle. Min/max to be determined.

  • Throttle: Supplied in meters/second desired speed. The ship will accelerate at a rate of (TBD) until desired rate is achieved (up to maximum of TBD). You cannot move backward(negative speed). This makes noise! The faster you are moving, the louder your sub is.

Fire torpedoes!

You have two torpedo tubes, and an unlimited supply of torpedoes. When you fire one, it will take some time to reload, so your effective firing rate is 2/x(tbd) seconds. You don't have to specify which tube you're firing, the command will fire whichever is ready.

Torpedoes start off moving at the sub's current speed plus a small boost (to prevent detonation with firing sub). It then accelerates up to full speed. Torpedoes **home in* on any sub within their cone of vision, and will try to turn to hit whichever of these is the closest. Although a torpedo's max speed is higher than a sub's, it cannot turn as quickly, so evasive maneuvers need to be considered.

Torpedoes have distance sensors, and will blow up when they are within x(tbd) meters of a sub. This will destroy the sub, and be very audible. Torpedoes have a maximum travel distance of (tbd) meters, at which point they fizzle out and are no longer a hazard.

The Arena

The arena is a spherical area of ocean with the origin at the center and a radius of 1000m(?tbd). Coordinates are continuous. Subs will start near the perimeter, at 90 degree intervals around the equator. They will start facing the center, with teammates 180 degrees apart. Moving outside the sphere is death, and will be audible.

Now obviously I've still got some work to do here, but as usual any comments are welcome. Well, most comments are welcome.

  • 1
    \$\begingroup\$ How does the movement work? Angle adjustments applied first and then a single linear step? (Making sure that everyone can easily predict their own position is essential to not having people complaining that they didn't move outside the sphere). \$\endgroup\$ – Peter Taylor Aug 7 '14 at 22:13
  • \$\begingroup\$ @PeterTaylor Yes, turns both horizontal and vertical applied before the step forward. On that note, I've thought about getting rid of the sphere and making it toruslike, but I'm undecided. \$\endgroup\$ – Geobits Aug 7 '14 at 22:22
  • \$\begingroup\$ I think that making it wrap (which I assume is what you mean) would be a conceptual headache when it comes to interpreting pings and trying to integrate longitudinal data. \$\endgroup\$ – Peter Taylor Aug 7 '14 at 22:25
  • \$\begingroup\$ @PeterTaylor Agreed, that's why it's a sphere as it is. If I could think of a good way to do it without making the boundary insta-kill, though, I would. Just avoiding the walls might be enough to put some people off, since turns aren't instant and you have to figure out your turn radius from your current speed. \$\endgroup\$ – Geobits Aug 7 '14 at 22:28
  • \$\begingroup\$ One way would be to introduce a speed limitation beyond the boundary, but that would require very careful explanation to ensure that everyone's simulations agree. (Actually, on the subject of simulations agreeing: you might need to say something about using strictfp in languages like Java). \$\endgroup\$ – Peter Taylor Aug 8 '14 at 8:38
  • \$\begingroup\$ One possibility for the boundary: Instead of killing you it just prevents you from moving outside it and makes a loud noise when you bump into it or scrape along it. \$\endgroup\$ – trichoplax Aug 10 '14 at 19:52
  • \$\begingroup\$ Instead of making the boundary itself insta-kill you could just surround the arena with mines which increase in density the farther away from the center you travel. \$\endgroup\$ – ccarton Aug 25 '14 at 12:58

Realistic Stock Market

This is based off of this other challenge, but with a whole lot of added realism. I'm trying to add as much realism as possible. It is a challenge.

You are an entrepreneur in the stock market, having created your own hedge fund (correct term?). Your company buys and sells shares in other companies, but also sells shares in itself.

At the very end of the game, the money is redistributed: All the money you've earned* is split up amongst your shareholders. Likewise, you gain money from the companies in which you've invested. By selling shares in yourself, there is a trade-off between long- and short-term gains.

There is a finite amount of each stock in the game, and there is one type of stock per company (so one per entrant). Your bot will start out with 100 shares of each other company, along with 100*N shares of itself, where N is the number of entrants. Each bot will have an initial bankroll of 10000 * N. (This helps to ensure a sufficiently large initial stock price).

Buying and Selling

Buying and selling stock is done by placing buy and sell orders. Each time a buy/sell order is placed, it is matched with the existing buy/sells orders to complete the trade.

Here is an example of how the orders are matched with each other for one stock:

  Sell Orders:
   19 @ $20 - Bot A
   11 @ $21 - Bot B
  Buy Orders:
   06 @ $19 - Bot S #oldest is given preference 
   06 @ $19 - Bot Q
   13 @ $18 - Bot T
   22 @ $16 - Bot R

 New Order:
  Sell 26 @ $17 - Bot C
  Trades [06 @ $19 - Bot S] with a surplus of 20
  Trades [06 @ $19 - Bot Q] with a surplus of 14
  Trades [13 @ $18 - Bot T] with a surplus of 01
  No more matches

  Sell Orders:
   01 @ $17 - Bot C #the remainder of the sell order
   19 @ $20 - Bot A
   11 @ $21 - Bot B
  Buy Orders:
   22 @ $16 - Bot R

In this particular example, Bot C will manage to sell 26 shares for 12*19+13*18+1*17 = $479, assuming that someone will eventually buy that one remaining share. The bot receives $462 at the end of his turn, and would receive the $17 at the end of the buyer's turn. If the share is not bought in the time between one turn and the next, the bot would receive that remaining share back.

The Tournament Setup

The tournament will be composed of 10 games, with each game consisting of 365 trading rounds. Each trading round will consist of one turn for each bot, with the bots in a randomized order.

There is nothing special that happens between any particular round. This helps to smooth out game flow so that each bot will have equal opportunity on their turn.

At the end of each game, the money of each competitor is redistributed to its stock holders (how much of the money?).

The winner of the tournament will be the bot with the highest average amount of money at the end of each game.

A Single Turn

For each stock, the bot will receive the buy and sell orders available.

At the start of every bot's turn, that bot's previous unfulfilled sell/buy orders will be canceled. (Is this a good idea?). Any unsold stock or unspent money is returned to the player.

Then, the bot will output the list of buy/sell orders it would like to place. The bot will be able to place one buy/sell order per stock. The bot must be able to immediately set aside the shares/money to support the order.

The controller program will look through your sell and buy orders sequentially and will remove the assets from you that are required for the transaction. If you have insufficient funds, that order will be ignored completely.

Then, the orders will be processed. Orders that match the already-existing orders will allow the transaction to occur after the bot's turn. Orders that are unmatched will remain on the market until the start of the bot's next turn.

Recording the past

Your bot is allow to create 1 text file to maintain a history of stock prices.


Input will consist of 3 arguments in this order:

Current round number, which is a number 1-365
Which stock ticker is for your company
A list of the data for each stock

The data for the stocks will be formatted like this:

"[stock ticker #1],[quantity 1],[price 1],[quantity 2],[price 2] [stock ticker #2],[quantity 1],[price 1],[quantity 2],[price 2]"

Each quantity/price pair represents one buy or sell order. Sell orders have positive quantity, while buy orders have negative quantity.

The order of the stocks will be randomized, but the stock tickers will remain consistent for the whole game.

(I was also think of including some more data in here, what else might be needed? Data on the assets of all the other competitors?)


Output will consist of many lines, each line formatted like so:

[stock number 1-N] [action] [quantity] [price]

The stock number is a number 1-N representing which stock to buy or sell. The action can be either b for buy or s for sell. The quantity and price can be any positive integer.


I want price to have 2 decimal digits, but I don't know if that would exclude anything or make it unnecessarily complicated. Right now, the prices are limited to integers. There is approximately $50 for each stock in the game, in an attempt to increase smoothness.

We need to balance the number of actions allowed per turn with the number of rounds in a game. Right now, the player can make 1 order per stock in a single round, which may make the time flow too roughly. The more rounds played, and the fewer actions allowed per turn, the smoother the game will be.

*We need to determine exactly how the money is redistributed. I initially had the idea that all the money will be redistributed equally to each stock, so a player who sells all the shares in himself keeps none of the money he earned in game and only gets the money from the other stocks. I think it might make more sense to only distribute profits, but we would have to determine how much of the profits are redistributed to shareholders.

Is it a good idea to have orders cancel after a period of time? Currently, a bot's orders are cancelled upon that bot's next turn. If we reduce the number of moves per turn, then we would want to increase the longevity of the orders. Alternatively, we could make orders permanent and irrevocable, only being cancelled at the end of the game.

  • \$\begingroup\$ If you give priority to orders that are older, then it makes sense to let orders persist beyond one turn. \$\endgroup\$ – trichoplax Aug 14 '14 at 18:07
  • \$\begingroup\$ Alternatively you could give priority to larger orders, in which case the priority would not affect your decision on whether to cancel orders after one turn. \$\endgroup\$ – trichoplax Aug 14 '14 at 18:08
  • 1
    \$\begingroup\$ The number of decimal places is largely irrelevant - a fixed number of decimal places is equivalent to integer. It's probably easier to model as integers internally, even if you display as 2 decimal places. You could just state that prices are in pennies/cents. \$\endgroup\$ – trichoplax Aug 14 '14 at 18:10
  • \$\begingroup\$ If a bot is limited in the number of buy and sell orders it can place by its available funds and shares, then that might be enough. If someone does decide to place a buy order on every single company, that will mean spreading their funds thinly as they cannot place buy orders that sum to more than the cash they have available. This naturally limits the activity level each turn. \$\endgroup\$ – trichoplax Aug 14 '14 at 18:14
  • 2
    \$\begingroup\$ I would recommend allowing orders to be placed and cancelled at any time. I don't think a restriction is necessary. What might make it more interesting is to introduce a cost to buying and/or selling. This should make strategy more important. \$\endgroup\$ – trichoplax Aug 14 '14 at 18:16
  • \$\begingroup\$ Costs could be of two types: a percentage commission on each successful sale or purchase, and also a fee for placing or cancelling an order. So bots will have to weigh up their options - to cancel an order they are uncertain they still want or leave it open to avoid a fee. \$\endgroup\$ – trichoplax Aug 14 '14 at 18:18
  • \$\begingroup\$ There's also a big decision to be made on how the market works. At present the prices are based purely on speculation of what those same prices will be in future. The alternative is to also have some non-player companies modelling companies selling products rather than just investing. Say 4 companies, one each for flour, eggs, rice and treacle. Those companies pay out dividends based on the randomly varying company profit, then bots use that income to pay out dividends based on how well they did out of the companies they are invested in. \$\endgroup\$ – trichoplax Aug 14 '14 at 18:24
  • 1
    \$\begingroup\$ I think that making each bot specify up front how much it will pay out in dividends would be good. It adds some asymmetry in round 1 (so it's not just picking a random share to buy). Probably do it in integer permille and round down when the time comes to distribute. It might even be interesting to make dividend payouts quarterly so that they don't just affect the final score. \$\endgroup\$ – Peter Taylor Aug 14 '14 at 19:43
  • \$\begingroup\$ I'd like to see the dividend percentage able to be changed, so that bots can decide to start paying out more/less at certain intervals. Maybe once a quarter. \$\endgroup\$ – trichoplax Aug 15 '14 at 17:15
  • \$\begingroup\$ So the bots are just buying and selling shares of each other, not any outside entity? What reason is there to choose one bot to invest in over another? Player decisions that someone's bot idea looks promising? \$\endgroup\$ – xnor Aug 20 '14 at 0:29
  • \$\begingroup\$ @xnor There are a few ideas to kick-start trading which have not been decided on yet, such as allowing the bots to announce the permille they will pay in dividends. \$\endgroup\$ – PhiNotPi Aug 20 '14 at 1:11

Brainfuck compression

Possible Duplicate

As it stands, this challenge could be labelled as a duplicate of others, as it is a base conversion. Please suggest ways of avoiding this in the comments. (Perhaps make interpreting the compressed code part of the challenge?)


For many code golfers, Brainfuck is the language of choice. However, it is horrifyingly wasteful: it only uses eight symbols (.,<>+-[]) out of a character set of 256.

Your task is to convert it into a compressed format, as follows:

  1. Receive Brainfuck code on standard input or equivalent.
  2. Remove characters which are not .,<>+-[].
  3. Convert [ to 000, ] to 001, + to 010, - to 011, . to 100, , to 101, < to 110 and > to 111.
  4. Group the resulting string into bytes, e.g. ,[.,] becomes 10100010 01010011.
  5. If the last "byte" is fewer than 8 bits long, add ones until it is 8 bits long. (Note: these may get interpreted as > instructions when the code is run or decompressed, but since they are at the end of the program, it doesn't matter.)
  6. Output the bytes to standard output.

Note: If the input does not contain any Brainfuck characters, the output should be empty.


Could this challenge include decompression as well?

Would a separate challenge for decompression or directly interpreting the compressed code be a duplicate?

Possible bonuses: -50 for removing <>, ><, +-, -+ from the code (golfing)

  • 1
    \$\begingroup\$ Nice challenge! I think it would be appropriate to include decompression aswell personally. The NULL byte could be an issue, especially for C programmers, but as you said, as long as you don't use two consecutive [s, everything should be okay \$\endgroup\$ – Christoph Böhmwalder Jul 24 '14 at 7:07
  • 2
    \$\begingroup\$ Also, you might add information about how non-brainfuck characters should be handled (e.g. if you provide abcd as input) \$\endgroup\$ – Christoph Böhmwalder Jul 24 '14 at 7:10
  • \$\begingroup\$ @HackerCow I'm trying to keep it simple, so I'm not sure about the decompression or interpreting. As a pure code-golf, would you just ask for two programs? (could be separated into two questions) Alternatively, it could be a code-reuse challenge, where the compressor and the decompressor/intepreter have to be as similar as possible (score=program1length+program2length+levenshteindistance) \$\endgroup\$ – user16402 Jul 24 '14 at 7:17
  • \$\begingroup\$ Well you could potentially ask this one now and post a "sequel" to it later, handling the decompression part. The code-reuse would also be a great idea, but that would definetely be a challenge ;) \$\endgroup\$ – Christoph Böhmwalder Jul 24 '14 at 7:21
  • \$\begingroup\$ @HackerCow I'm worried that a separate decompression challenge might be a dupe of this one... \$\endgroup\$ – user16402 Jul 24 '14 at 7:23
  • \$\begingroup\$ True, although I have seen sequels to questions before, so I don't think it would be a problem... Some mod might be able to help here \$\endgroup\$ – Christoph Böhmwalder Jul 24 '14 at 7:24
  • 1
    \$\begingroup\$ @professorfish You could ask for two programs/functions, and take the sum of both lengths as score. \$\endgroup\$ – ProgramFOX Jul 24 '14 at 10:26
  • \$\begingroup\$ @ProgramFOX True, but if the two programs aren't really connected, maybe it is better to have two separate challenges - the only problem is that they might be considered dupes...??? \$\endgroup\$ – user16402 Jul 24 '14 at 14:00
  • \$\begingroup\$ @professorfish Yes, they might be considered dupes, as a decompressing algorithm for this is probably the compression one reversed. But if you don't like having both in one challenge, you can also create a compression challenge without decompression. \$\endgroup\$ – ProgramFOX Jul 24 '14 at 14:37
  • \$\begingroup\$ This is just a base conversion with unusual digits, so it's essentially a duplicate of codegolf.stackexchange.com/q/4423/194 \$\endgroup\$ – Peter Taylor Jul 24 '14 at 15:01
  • \$\begingroup\$ @PeterTaylor There is a base conversion involved, although it isn't the only thing there is. would having the user create two programs, a compressor and an interpreter of the compressed data, be better? \$\endgroup\$ – user16402 Jul 24 '14 at 15:10
  • \$\begingroup\$ Ok, the compression also involves a filter, but that's a trivial pre-processing step before the base conversion task which has already been done. IMO base conversion is a trivial task per se, and since Interpret BF has been done I would regard an interpreter of the compressed data as also being a dupe. See also meta.codegolf.stackexchange.com/q/1571/194 \$\endgroup\$ – Peter Taylor Jul 24 '14 at 15:15
  • \$\begingroup\$ @PeterTaylor OK. "Alternatively, it could be a code-reuse challenge, where the compressor and the decompressor/intepreter have to be as similar as possible (score=program1length+program2length+levenshteindistance)" - is that a dupe as well? \$\endgroup\$ – user16402 Jul 25 '14 at 7:32
  • 1
    \$\begingroup\$ @Kroltan so the longer the decompressor the better? \$\endgroup\$ – user16402 Jul 26 '14 at 6:42
  • 1
    \$\begingroup\$ I think this would be less likely to be considered a duplicate if the method of compression was not so strictly defined. For example, allowing the use of Huffman coding instead of fixed length 4 bit codes may allow better compression for programs of non-trivial length. You could allow people to come up with their own method of compression and including the compressed sizes of a list of test programs in their score. Alternatively you could base the score purely on the compressed size and not limit the size of the compression program. \$\endgroup\$ – trichoplax Jul 28 '14 at 22:15

You must log in to answer this question.

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