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]

| |

2966 Answers 2966

3 4 5

Array Pattern Matching Language

Everyone is (or should be) acquainted with the ways of the regular expression. At its core, a regex is made for matching strings. However, it's just matching something, right? Why not match arrays? That would be something!


Your task now is to design and implement a new numeric array pattern-matching language. The only requirement is that your created language satisfies the mandatory tasks detailed below. However, this being a popularity contest, you may wish to opt for the bonus tasks and maybe even some competitive golfing value.

To be more precise, your language should be able to take patterns and match them against arbitrary arrays of integers. They should minimally be used to determine whether or not an array matches the pattern. This can be done by return a boolean, two different strings, etc.


As a voter, you should keep in mind the criteria mentioned, and ask yourselves these questions:

  1. Is the language trivial? That is, is there a lot that can be done other than the detailed tasks, or is the language minimally designed for these tasks?
  2. Is it well described? Does the author explain the solutions and the concept behind the language?


(Thanks to Nathan Merrill for a lot of tasks!) Note that, for each task, the empty array can go in either category, unless otherwise stated.

1. That's odd!

Write a program in your language that will match the input array if all of its members are odd; otherwise, do not match.

 [1, 3, 5, 11, -1]
 [5, 9, 1023, 3243]

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

2. Increasing in membership

Match an array that has each member more than the previous member.



3. Bodyguards

Match only arrays with a 0 on both sides.

 [0, 1, 2, 0]
 [0, 5, 0]
 [0, 0]

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

4. Mountain

Match all arrays of the form [1, 2, 3, ..., N-2, N-1, N, N-1, N-2, ..., 3, 2, 1], for any N.

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

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

5. Shifting, 1 to 5

Match only arrays that consist of the numbers 1, 2, 3, 4, 5, 4, 3, 2 "in order", where the elements can be rotated around the array.

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

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

6. Not in my prime

Match an array if and only if all of it's members are not prime.

 [4, 6, 8, 9, 24]
 [20, 40, 42, 45]
 [1, 10, 100]

 [1, 100, 200, 300, 400, 401]
 [2, 3, 4]
 [2, 4, 8]
 [3, 5, 7]

7. Unique

Match only arrays that contain no duplicates.

 [1, 2, 3, 4]
 [5, 15, 25]

 [3, 4, 5, 3]
 [10, 11, 10, 13]
 [2, 2]

8. Not close

Match only arrays that, for each member N, do not also have a member N+1.

 [1, 3, 45, 30]
 [20, 23, 26]

 [200, 201, 202]
 [3, 9, 100, 4]
 [2, 4, 5]
 [0, 1]

9. Arithmetic Progression

Match only arrays that are arithmetic progressions; i.e. there elements increase by a constant factor. (Singletons may go either way.)

 [2, 6, 10, 14]
 [5, 10, 15, 20]
 [20, 19, 18]
 [1, 2, 3]
 [5, 6, 7, 8]

 [5, 25, 125]
 [2, 6, 5]

10. Fibonacci-esque

Match only arrays (of length greater than 2) where each element is the sum of the previous two (not counting the first 2), and match all arrays of length 2.

 [100, 1, 101, 102, 203, 305, 508, 813]
 [-5, 5, 0, 5, 5, 10, 15, 25, 40]
 [2, 1, 3, 4, 7, 11]
 [0, 0, 0, 0, 0, 0]
 [1, 0, 1, 1, 2]
 [1, 2, 3, 5]
 [10, 2]

 [5, 10, 15, 20, 25]
 [91, 32, 32]
 [5, 5, 5]

11. Self-descriptive

Match arrays that contain their lengths.

 [12, 2]
 [4, 3, 2]

 [123, 122, 121]
 [0, 2, 4, 6, 8]

12. Palindrome

Match all palindromic arrays. That is, arrays that are the same when reversed.

 [2, 3, 4, 3, 2]
 [-1, -1]

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

13. Kth element at most K

(You can use 1-based or 0-based indexing. I will give test cases for 0-based indexing.)

Match all arrays whose Kth element is at most K.

 [0, 0, 2]
 [0, 0, 0, 1]
 [-4, -1, 0]

 [2, 42]
 [-4, -92, 4]

14. Twins

Match all arrays of even length whose first half is equal to the second half.

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

 [4, 9, 9, 4]
 [9, 2, 13, 2, 9]
 [1, 2, 3, 1, 2]

15. A simplified date

Match all 3-element arrays which constitute a valid date. The array will be [year, month, day]. That is, year >= 0, 1 <= month <= 12, and 1 <= day <= 31.

 [2018, 6, 16]
 [1990, 1, 1]
 [0, 6, 31]
 [3014, 7, 13]
 [1293, 9, 9]
 [12, 12, 12]

 [-4, 12, 9]
 [100, 100, 4]
 [1929, 13, 31]
 [4102, 12, 32]
| |
  • \$\begingroup\$ I look forward to the answers for this as I would like to have a generalized regex feature in Pytek. :D \$\endgroup\$ – El'endia Starman Feb 9 '16 at 20:23
  • \$\begingroup\$ [] is a match for "all members are odd". \$\endgroup\$ – Peter Taylor Feb 9 '16 at 20:37
  • \$\begingroup\$ @PeterTaylor Ah right, drinker's fallacy. \$\endgroup\$ – Conor O'Brien Feb 9 '16 at 22:22
  • \$\begingroup\$ Can the input be in unary? \$\endgroup\$ – Downgoat Feb 9 '16 at 23:33
  • \$\begingroup\$ @Downgoat That would hardly be interesting, I don't see why not, but it'd be hardly useful and largely unable to compensate for negative numbers. \$\endgroup\$ – Conor O'Brien Feb 9 '16 at 23:34
  • \$\begingroup\$ Some of the tasks seem to use matching in the sense of a regex: the array as a whole either matches or does. Others seem to describe a filter, where the individual elements of the array are matched or not and the matched ones are output. If this is intentional, it would be good to mention it in the Description section. \$\endgroup\$ – Peter Taylor Feb 11 '16 at 16:06
  • \$\begingroup\$ I really like the concept of this challenge. However, I'd recommend standardizing your test cases: 1. Make your regex an all/nothing match (as Peter Taylor explained). 2. Ensure that your array only contains integers (no matrices). Then, adding more test cases would be fantastic. \$\endgroup\$ – Nathan Merrill Feb 11 '16 at 20:52
  • 2
    \$\begingroup\$ Possible test cases: Match if each 0 has a positive integer on both sides. Match the array [1,2,3,...N-1, N, N-1, N-2...3,2,1]. Match the array [1,2,3,4,5,4,3,2] and [2,3,4,5,4,3,2,1] and [3,4,5,4,3,2,1,2] and so on. Match an array with only unique elements. Match an array that doesn't contain both an N and an N+1. Match the fibonacci sequence with an arbitrary first two numbers. Match if all of the numbers aren't prime. \$\endgroup\$ – Nathan Merrill Feb 11 '16 at 21:11
  • \$\begingroup\$ Some task ideas (although you seem to have quite many already): Palindromic arrays. Even-length arrays whose first half equals second half. Arrays whose kth element is at most k. Arrays that contain their length as an element. \$\endgroup\$ – Zgarb Jun 22 '16 at 18:05
  • \$\begingroup\$ @Zgarb on the first half equals second half, do you mean arrays like [1, 2, 1, 2]? \$\endgroup\$ – Conor O'Brien Jun 22 '16 at 19:22
  • \$\begingroup\$ @CᴏɴᴏʀO'Bʀɪᴇɴ Yes, exactly. \$\endgroup\$ – Zgarb Jun 22 '16 at 20:58
  • \$\begingroup\$ It seems all the elements are integers and not floats. If that's the case,, you should say so. I think "Is the language trivial?" would be better stated positively, saying that the language constructs are powerful in general, not just tailored to the examples given. \$\endgroup\$ – xnor Oct 4 '16 at 1:22
  • 1
    \$\begingroup\$ It seems to me that such a language already exists--it's called Jelly. ;) (And APL, and J.) Wisecracking aside, there are two serious points I want to make: 1) What do you expect submissions to bring to the table that existing languages don't have? Why design a language for this set of tasks when it's essentially already been done? 2) In any case, you should stipulate in the question that submissions must be new languages created specifically for this challenge. \$\endgroup\$ – DLosc Oct 4 '16 at 7:48
  • \$\begingroup\$ @DLosc I'm thinking of a regular expression language, so it should be somewhat similar to regex. How might I define that in a strict sense? \$\endgroup\$ – Conor O'Brien Oct 5 '16 at 2:49
  • \$\begingroup\$ Well, you could read up on regular languages, but I suspect that isn't what you want, since several of your tasks can't be matched by a regular language. (Unique, self-descriptive, and twins, e.g.) Instead, you may be looking for a declarative language, though that still isn't a really "strict" category and you'd have to further specify what you mean by declarative. \$\endgroup\$ – DLosc Oct 5 '16 at 4:41

🎲🎲Lucky Dice (KotH, WIP)🎲🎲


You have recently taken a job at Lucky & Co, as a professional dice roller, and need to make as much money as you can! (of course). You will be paid exactly what you roll, $1 for a 1, $2 for a 2 etc. Where's the fun in that? Well, these aren't ordinary dice: starting with $5 in your bank, you must purchase new dice, which will all be rolled each turn. There are many different types of dice, all with different probabilities of rolling the different numbers. Every turn, you take a look at what the dices have done for you, then decide what to invest in. But beware! You have many rivals, all with the same aim in mind, and there are only so many dice in the shop...

The Dice (StC)

There are many types of dice, which can be split into the following categories:

Basic Earners

20 of each are available, they are simply rolled and their value is added to the total points:

║ ID ║     Description     ║ Price ║  1  ║ 2  ║ 3  ║ 4  ║ 5  ║  6  ║
║  0 ║ Rolls a 1           ║     1 ║ 100 ║  0 ║  0 ║  0 ║  0 ║   0 ║
║  1 ║ Likely to be low    ║     3 ║  50 ║ 25 ║ 13 ║  7 ║  3 ║   2 ║
║  2 ║ Unlikely to be high ║     6 ║  22 ║ 22 ║ 22 ║ 11 ║ 11 ║  11 ║
║  3 ║ Even chances        ║     9 ║  17 ║ 17 ║ 17 ║ 17 ║ 17 ║  17 ║
║  4 ║ Unlikely to be low  ║    12 ║  11 ║ 11 ║ 11 ║ 22 ║ 22 ║  22 ║
║  5 ║ Likely to be high   ║    16 ║   2 ║  3 ║  7 ║ 13 ║ 25 ║  50 ║
║  6 ║ Rolls a 6           ║    21 ║   0 ║  0 ║  0 ║  0 ║  0 ║ 100 ║


These multiply the points gained by the basic dice by something between 0.33 and 18... 10 of each are available. r represents what it rolled, each outcome (1-6) is equally likely:

║ ID ║   Description   ║ Price ║
║  7 ║ Multiply by r/3 ║    10 ║
║  8 ║ Multiply by r/2 ║    13 ║
║  9 ║ Multiply by r   ║    22 ║
║ 10 ║ Multiply by r*2 ║    34 ║
║ 11 ║ Multiply by r*3 ║    50 ║


These dice, with 10 of each available, are what makes the game truly interesting. They handle user interaction: each has a set action that it applies to one other random player (except 16):

║ ID ║              Action              ║ Price ║
║ 12 ║ See below (too long)             ║    35 ║
║ 13 ║ They get 10 less (not below 0)   ║    45 ║
║ 14 ║ Like 12, but you get the points  ║    60 ║
║ 15 ║ They get 25 less (not below 0)   ║    60 ║
║ 16 ║ Like 14, but you get the points  ║    90 ║

12: A fair dice, the value of which is subtracted from every other users' basic dice roll (not below 0).


Miscellaneous other bonuses and actions, each with a 50% chance of happening. There are only 3 of each available:

║ ID ║                Description                ║ Price ║
║ 17 ║ Protects you from attacks                 ║    65 ║
║ 18 ║ Roll every basic die again                ║    90 ║
║ 19 ║ Roll every basic and multiplier die again ║   110 ║
║ 20 ║ Square your score                         ║   120 ║
║ 21 ║ Cube your score                           ║   170 ║

How the dice fall

When working out the points for a round:

  • Every players' coins are flipped. The results are remembered.
  • Every players' basic dice are rolled (as many times as specified by coins). The total of the results for each player is that players' points for this round
  • Every players' multiplier dice are rolled (with extra rolls). Each multiplication is applied on top of the previous one.
  • Any squaring or cubing is applied.
  • For every players' attack dice, a random other player is chosen for each. Unless that player had a shield, the appropriate action is taken.

A game

A game lasts until first place is 200 points ahead of second place, or until 500 rounds have been played. There are 7 people in each game, who each start with just $5. Every round, each player submits a list of dice that they want to buy. If they ask for a dice that isn't there, ask to pay more than they have, or returns an otherwise invalid move, they do not buy anything that round. If more people ask for a dice than there are of that dice, no-one gets it. After every bot has given their move, and all orders have been resolved, the points for the round are calculated as above, and then added to the total score of each bot. At this point, the win condition is tested. 1st place gets 7 points, second gets 6 and so on. If two players are joined in, for example, 3rd place, they both get 5 points, but the next bot/s get only 3.

A tournament

In a tournament:

  1. If there are more than 7 bots, the bots will be divided into groups of 7 to play until every bot has played an equal number of games, and there are 7 bots which have a higher total score than the rest.
  2. The top 7 bots play games until one has 50 more points than second place.
  3. 2 is repeated for all the other groups of seven, and then the leftover bots. Now every bot knows its rightful place!

I will run a tournament every day if possible, which it hopefully will be.


You will write a Python class that inherits from Bot, and implements get_orders, which must accept the following parameters:

  • money - how much money each player has (a tuple of ints)
  • dice - what dices each player has (a tuple of tuples of ints)
  • index - your index in the money and dice tuples (an int)`
  • shop - how many of each dice the shop has (a dict of int: int pairs)

Dice are represented in the above by their ID. You may also implement __init__ (self, random), where random is a random.Random object, which is the only access to randomness that you are allowed, that is, if I were to run your code again with the same argument to random and the same calls to get_orders, I would receive the same results. You may also implement any other utility functions you wish. You may not store information between games (already banned but let's do it explicitly), and you may not mess with the controller. You may not team up (how could you?) or use any other competitor's code without significant changes without their permission. You may not programmatically invoke another competitor's code, because that could get circular...




None yet ;P


  • Any thoughts?
  • What should I clarify, I feel like I've missed everything...
  • Do you like the idea?
  • Have you spotted a perfect and unbeatable strategy?
  • Any suggestions for new dice/dice types?
  • Any suggestions for changes to the game/tournament system?
  • Are all the tags appropriate?

    Unicode Art Table

║ ID ║                Description                ║ Price ║
║ 16 ║ Protects you from attacks                 ║    65 ║
║ 17 ║ Roll every basic die again                ║    90 ║
║ 18 ║ Roll every basic and multiplier die again ║   110 ║
║ 19 ║ square your score                         ║   120 ║
║ 20 ║ cube your score                           ║   170 ║

MathJax Table

\begin{array} {|r|r|} \hline \text{ID} &\text{Description} &\text{Price} \\ \hline \text{16} &\text{Protects you from attacks} &\text{65} \\ \text{17} &\text{Roll every basic die again} &\text{90} \\ \text{18} &\text{Roll every basic and multiplier die again} &\text{110} \\ \text{19} &\text{Square your score} &\text{120} \\ \text{20} &\text{Cube your score} &\text{170} \\ \hline \end{array}

Which is better?

| |
  • 2
    \$\begingroup\$ Upvote this comment for MathJax tables. \$\endgroup\$ – Artemis still doesn't trust SE Apr 22 '19 at 11:34
  • 5
    \$\begingroup\$ Upvote this comment for Unicode art tables. \$\endgroup\$ – Artemis still doesn't trust SE Apr 22 '19 at 11:35
  • \$\begingroup\$ In your "Attacks" table, you want "halve their score" instead of "half their score." \$\endgroup\$ – AdmBorkBork Apr 22 '19 at 12:43
  • \$\begingroup\$ I have given suggestions in the chat room \$\endgroup\$ – Beefster Apr 22 '19 at 17:28
  • \$\begingroup\$ "A game lasts until first place is 50 points ahead of second place, or until 200 rounds have been played." Nobody will ever buy the big dice with this rule in play. \$\endgroup\$ – Beefster Apr 22 '19 at 17:29
  • \$\begingroup\$ @Beefster Been running a few tests... I bot that just buys all the ID: 0 (roll-a-one) dice gets 20 per turn, and over 200 turns that's 4000 points. A few less to allow for the time it takes to buy them, and of course other bots will be playing, but still... I'll be thinking about it, and the "first place is 50 points ahead of second place" is definitely wrong. \$\endgroup\$ – Artemis still doesn't trust SE Apr 25 '19 at 14:31
  • \$\begingroup\$ Why not just cut out the "way ahead" end condition and just make it a constant number of rounds? \$\endgroup\$ – Beefster Apr 25 '19 at 17:02
  • \$\begingroup\$ @Beefster The idea was that it should end with the way ahead condition, but the round limit prevents it from going on forever. I'm not sure about that anymore though. \$\endgroup\$ – Artemis still doesn't trust SE May 2 '19 at 14:18

Round away from zero


Inspired by Round towards zero.

Given a number input via any reasonable method, round the number "away from zero" - positive numbers round up, and negative numbers round down.

You can output a floating-point number with the decimal point (e.g. 42.0) if desired.

why did i think this was a good idea

Test cases

-99.9 => -100
-33.5 => -34
-7    => -7
-1.1  => -2
0     => 0
2.3   => 3
8     => 8
99.9  => 100
| |
  • \$\begingroup\$ It's a great idea, because truncation-based methods from the original won't work quite as well, but there's still plenty of room to be clever. \$\endgroup\$ – Unrelated String Aug 26 '19 at 23:58
  • 2
    \$\begingroup\$ I'm not certain if this is a dupe, since most answers to this can be an answer from the inspiration but with +sign(input) tacked on. I think that may be competitive in too many languages. \$\endgroup\$ – FryAmTheEggman Aug 27 '19 at 15:03
  • 3
    \$\begingroup\$ @FryAmTheEggman Actually, that solution would give incorrect answers for all integers except 0. \$\endgroup\$ – Joel Aug 27 '19 at 23:02
  • \$\begingroup\$ The test case inputs may have a better coverage for all cases: [-99.9, -5, -2.0, -1.1, 0, 0.0, 1.1, 2.0, 5, 99.9]. \$\endgroup\$ – Joel Aug 27 '19 at 23:27
  • \$\begingroup\$ @Joel That is true, and I guess also adding a check for being an integer is probably different enough in most languages? I'll leave my comment in case another similar problem emerges but it is likely that someone will make the same mistake I do, so it may be a good idea to specifically say this won't work in the challenge. \$\endgroup\$ – FryAmTheEggman Aug 28 '19 at 0:30
  • \$\begingroup\$ @FryAmTheEggman brings up a good point though, what's stopping people from doing something like +sign(input%1) to trivialize the challenge? Maybe I shouldn't post this after all \$\endgroup\$ – Value Ink Aug 28 '19 at 21:35
  • \$\begingroup\$ @Value Ink The outcome of the modulo operation varies in different programming languages when a negative number is involved (see the big table at the right side of the wiki page). Your solution can only give correct answers in some languages. This is actually a good task to make people aware of that. By the way, the first and third test cases yield wrong results. \$\endgroup\$ – Joel Aug 29 '19 at 3:20
  • 1
    \$\begingroup\$ I really like this challenge. It is very easy to understand and the implementation is not as trivial as it initially seems. I do think that you should include some non-decimal test cases like @Joel suggested, such as -5 and 5. \$\endgroup\$ – Jitse Aug 29 '19 at 8:10
  • \$\begingroup\$ @Jitse won't that be hard for people whose languages are strongly typed or something? Although I guess they can just do -5.0 anyways. Ok, I've changed them. \$\endgroup\$ – Value Ink Aug 30 '19 at 0:15
  • \$\begingroup\$ You may add a note saying that the returned answer can be a float (like 5.0) or an integer. \$\endgroup\$ – Joel Aug 30 '19 at 1:42
  • \$\begingroup\$ @Joel good idea. Thanks for the tip \$\endgroup\$ – Value Ink Aug 30 '19 at 2:02
  • \$\begingroup\$ I just wonder, is it appropriate for me to post solutions after getting involved in improving the challenge? \$\endgroup\$ – Joel Aug 30 '19 at 2:47
  • 2
    \$\begingroup\$ @Joel I'm not sure (I assume it's fine), but if the dilemma is nagging you I think it's best if asked as a separate meta post and not as a comment in here... \$\endgroup\$ – Value Ink Aug 30 '19 at 2:58
  • \$\begingroup\$ Now that this has been posted, it would be best to delete it, to free up space \$\endgroup\$ – caird coinheringaahing Sep 4 '19 at 9:07

Win the competition

Write a Javascript anonymous function that, given two functions as strings, deterministically picks one as the winner and returns 1 if the first input wins and 2 if the second input wins. The choice must not depend on the order of inputs (that is, for any given input pair, the same program must always win no matter which one is first).

Every submission will be used to compare all unordered pairs of all solutions except self. Every time a program is chosen as the winner, it is assigned 1 point.

Submissions must not store any information between runs, interfere with the controller or somehow destroy my computer. There is no hard time limit, but intentionally creating an excessively slow solution counts as destroying my computer. Submissions must not duplicate other submissions or be longer than 200 KiB. Submissions must not rely on the input functions always halting (that is, they must not execute them or any parts of them).

You should give your submission a name (it should match the regex [A-Za-z ]+ and not coincide with any other solutions).

Controller in a snippet:


This is tagged . Whoever wins the most wins!

After posting this, I will post two example (community wiki) answers: one that compares in lexicographic order, and another that compares first by byte count, then in lexicographic order (the reason for posting two is that at least 3 programs are needed for anyone to get any points).

Sandbox stuff

  • How can I prevent the last answer from always winning?
    • Will that happen automatically, once enough answers are posted that it's nearly impossible to optimize for all of them?
  • Would it be a good idea to introduce other requirements for the submissions, such as transitivity?
  • Would it be a good idea to introduce a per-user submission limit (probably 1 or 2)?
| |
  • 6
    \$\begingroup\$ That is a really fun idea but probably more a social- than a programming challenge:) I guess one problem is that newer submissions can always be tuned to favor themselves against all the existing ones, so it is probably gonna end up as a "last submission wins" if you don't include any counter measures. \$\endgroup\$ – flawr Nov 26 '19 at 9:06
  • \$\begingroup\$ I suggest a rule against randomness (and probably a language restriction, too, those make it a lot easier) \$\endgroup\$ – Redwolf Programs Nov 26 '19 at 13:55
  • \$\begingroup\$ @RedwolfPrograms I can see why is randomness bad, but why should I add the language restriction? I have thought about it, and know I will probably add it in the end (because I can write an automated tester only in some langauges), but does it actually improve anything? (I guess I'll restrict to one of Javascript, C# or Python; Javascript seems to be the most common so it is also the most likely) \$\endgroup\$ – the default. Nov 26 '19 at 14:23
  • \$\begingroup\$ @mypronounismonicareinstate No specific reason, but it tends to simplify things massively. It also allows the bots to more effectively read the source code \$\endgroup\$ – Redwolf Programs Nov 26 '19 at 14:48
  • \$\begingroup\$ To minimise the problem flawr mentions you could consider only showing a "peek" of the programs to be judged, and then include a suitable upper bound on length. Of course, this has the problem of choosing that upper bound, but I think it may lead to a better back-and-forth? Posting will also still have a negative effect on your ability to win, however. \$\endgroup\$ – FryAmTheEggman Nov 26 '19 at 19:34
  • 1
    \$\begingroup\$ Some languages make extensive use of non-ascii characters, and some languages don't support non-ascii characters as input. Restricting the language is one way to solve this problem. \$\endgroup\$ – 79037662 Nov 29 '19 at 17:13
  • \$\begingroup\$ You should post it, just to see how it goes. Five upvotes just in the sandbox...if you added a language restriction and a few more rules to prevent the last answer from always winning, I think it'd be a popular challenge \$\endgroup\$ – Redwolf Programs Dec 1 '19 at 23:08
  • 1
    \$\begingroup\$ Do we submit functions that take strings, programs that read from STDIN, or perhaps even functions that take functions? \$\endgroup\$ – Jo King Dec 2 '19 at 4:57
  • \$\begingroup\$ I feel like the "no hashing" condition might be a bit problematic: For the last program submitted not to have an easy time with the rest, the scoring method of a program needs to be very hard to predict and game, and hashes are basically the optimal way about this. This then might end up with a challenge where people try to implement almost-but-not-quite hashing functions without upsetting you. \$\endgroup\$ – AlienAtSystem Dec 14 '19 at 9:22
  • \$\begingroup\$ @AlienAtSystem I see your point; removed the hashing restriction and also a loophole (where a solution that is a few GiB large, but presumably full of comments so that it doesn't run too slowly, makes all others time out). \$\endgroup\$ – the default. Dec 14 '19 at 12:09


In the near future, the legal world is crumbling. If a case lasts longer than three days, the defendant is assumed to be guilty. Prosecutors create false evidence to get their guilty verdict or flawless record. Defense attorneys are forced to retaliate, claiming that the ends justify the means. In the trials and tribulations of the courtrooms of tomorrow, how will we ever get justice for all? This truly is the dark age of the law.

Luckily, the world has you. Just 11 short years ago, you were a ragtag rookie lawyer in a world of big fish, but you had potential and it showed. You always trusted your client, no matter how bad things looked. You were able to cut through the deception and reach the truth. When times got hard, you forced your biggest smiles. Of course, it was only 3 years before a little misunderstanding cost you your badge, but that's all cleared up now. You're back, ready to protect those no one else will and make miracles happen.

Except... You're pretty sick. For some reason you can't quite remember, you've got a crippling fear of cold medicine. Clearly, you're in no position to stand at the bench. If you can't be there to clear your client's name, you'll have to write a program to do it for you!

For this challenge, you'll be writing a program that can take your place in a cross-examination. There are three different things you need to keep track of: Facts, Evidence, and Statements.

  • Facts
    • There are 26 Facts, named A, B, C... Y, Z. Usually, only a small number of them will be relevant, but you must be able to handle all of them if necessary. Contrary to their name, a Fact can be either True or False.   You are never told the Facts, but you can figure them out from your...
  • Evidence

    • Evidence is the most important thing for you to have, because it's how you know the Facts. You could make the case* that Evidence is everything in court. Pieces of Evidence have a name and a description of their relevance to the Facts. Evidence comes in two flavours: Direct and Circumstantial. Direct Evidence proves a Fact, while Circumstantial Evidence proves a fact if and only if a condition is met.   You get your Evidence as input in this format:

      Direct Evidence
      Name of evidence: [Fact] is <true/false>.
      Circumstantial Evidence
      Name of evidence: If [Fact] is <true/false>, then [Fact] is <true/false>.
  • Statement

    • A Statement is a declaration of Fact by a witness. There are also two kinds of Statements: Absolute and Conditional. An Absolute Statement claims a Fact, while a Conditional Statement claims a Fact if and only if a condition is met. Statements are taken as input in the same format as the second half of a piece of Evidence.

Your job is to analyze your Evidence to determine the Facts, then try to find contradictions in the Statements.

A Statement can contradict either an earlier Statement or a piece of Evidence. If a Fact is proven to be True or False and the witness claims the opposite, that is a contradiction. Note that If A is true, then B is true. and If A is true, then B is false. do not contradict unless A is true.


Input comes from either stdin or a file, in exactly this format:

<One or more pieces of Evidence on their own lines>
<One or more Statements on their own lines>


If there is a contradiction between a proven fact and something the witness claims, you must find the first Statement that contains the contradiction. If it contradicts the Evidence, output this:

Objection! Statement n contradicts this piece of evidence:

followed by a space and the name of the contradicted Evidence. n is replaced with the number of the contradicting Statement (starting at 1). If, instead, the witness contradicts themselves, output this:

Objection! Statement n contradicts statement m.

n is replaced with the number of the contradicting Statement and m is the number of the contradicted Statement (both starting at 1. m < n).

If there are no contradictions, output this instead:

No objections, Your Honor.



My badge: L is true.
Thinker Clock: C is true.
Receipt: If C is true, then W is false.
A is true.
B is false.
If A is true, then W is true.
H is true.
C is false.


Objection! Statement 3 contradicts this piece of evidence: Receipt


Metal detector: B is true.
If B is true, then A is true.
A is false.


Objection! Statement 2 contradicts statement 1.


Stuffed animal tail: N is false
A is true.
N is false.


No objections, your honor.


  • The Evidence will never contradict itself. Evidence is infallible.
  • There will never be a logic loop (e.g. If A is true, then B is true., If B is true, then A is true.)

* If you know what I mean

| |
  • \$\begingroup\$ Objection! According to the first example, If A is true, then B is false is equivalent to If A is false, then B is true, however this would cause the statement about contradictions incorrect. More detail on the first example: C is false, so the assertion from the Receipt doesn't apply; W is true, since A is true. \$\endgroup\$ – cjfaure Jun 4 '14 at 16:59
  • \$\begingroup\$ Hold it! The Thinker Clock found at the scene proves that C is true! Since we know C is true, the Receipt shows that W is false! The witness claims that A is true in the first line of their testimony, but then says that if A is true, W has to be true! By indirectly claiming that W is true, their testimony contradicts the evidence! \$\endgroup\$ – undergroundmonorail Jun 4 '14 at 17:09
  • 1
    \$\begingroup\$ Wouldn't the Thinker Clock be the evidence being contradicted, then? There's more direct contradiction between the Thinker Clock and the last statement. \$\endgroup\$ – cjfaure Jun 4 '14 at 17:14
  • \$\begingroup\$ Of course, saying that C is False is a contradiction... *desk slam* but the challenge requires you to find the first statement to contain a contradiction! [Present -> Challenge Spec] It reads, and I quote, "...you must find the first Statement that contains the contradiction". Take that! \$\endgroup\$ – undergroundmonorail Jun 4 '14 at 17:21
  • \$\begingroup\$ Ace Attorney strikes again! \$\endgroup\$ – cjfaure Jun 4 '14 at 17:30
  • 1
    \$\begingroup\$ So basically this is a presentation of 2-SAT. The third example is wrong: statement 2 contradicts stuffed animal tail. And I agree with Trimsty that where you have a chain of reasoning there isn't a unique "contradicted Evidence", so I think that you should make it clearer what you mean by that. \$\endgroup\$ – Peter Taylor Jun 4 '14 at 20:48
  • \$\begingroup\$ @PeterTaylor I will figure out a way to formalize it better \$\endgroup\$ – undergroundmonorail Jun 4 '14 at 20:52
  • \$\begingroup\$ @githubphagocyte Yep, my bad. That was a typo. \$\endgroup\$ – undergroundmonorail Jun 4 '14 at 20:53
  • \$\begingroup\$ I feel like in many languages this scores for this will be dominated by string handling. \$\endgroup\$ – Martin Ender Jun 5 '14 at 15:57
  • \$\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:48

Sandbox note: This is an idea for a challenge based on the halting problem. As it is, it's hard to imagine it being popular on PPCG, but I'd really like to make it into something people would actually participate in. The reason is that it's really interesting from a theoretical point of view, as a fundamentally open-ended challenge. The beautiful mathematics of Turing and Gödel gurantees that there's always a new innovation that the cops could make, and there's always a way for the robbers to exploit it. So any ideas on how to turn this into something fun would be greatly appreciated.

HALT in the name of the law

The robbers are getting away, and the cops have to decide whether to wait for them to stop and arrest them, or set up a road block at the state boundary. They do this by trying to predict whether the robbers' program will halt. Please note that this challenge is hard, especially for the cops.

Robbers are represented by programs written in a language called "w", which I invented for this challenge, and which I describe below. w is easy to implement and relatively easy to reason about. I will provide a reference implementation and a macro preprocessor that allows it to be written in a somewhat human-readable form.

Cops must provide a program (in any language) that takes a robber's w program as input, and tries to decide whether it halts or not. A cop submission is invalidated by a robber program for which it returns the wrong answer or fails to terminate.


You must write a program that takes as input programs in the (pre-processd) w language. It should attempt to output a truthy value if its input program ever halts, and a falsy value if it doesn't. Your submission should be written in a "real" programming language rather than w. In addition to your program, you should provide a clear English explanation of how it works.


You must "crack" cops' submissions by providing one of the following three things:

  • A program written in w that halts, but for which the cop program does not return a truthy value. (The cops waited at the roadblock while you stopped, changed your identities and went underground.) You must demonstrate that the program halts, either by running it in the reference implementation of W or by proving that it has to halt eventually.

  • A program written in w for which the cop's program returns a truthy value, together with a proof that your program does not halt. (The cops gave chase, but you kept going until you reached the state border, infinitely far away.)

  • A program written in w for which the cop program itself doesn't halt, together with an argument showing that it doesn't halt. (The cops just gave up and got some donuts, hoping nobody would notice.)

Other rules

If the cops' program is nondeterministic (e.g. because it's doing some kind of stochastic search for halting conditions) then it suffices to show that there is some non-zero probability that it will return the wrong answer or fail to halt.

This is for the cops - the uncracked submission with the most votes wins.

The w language

Syntax and semantics

w is a very simple structured programming language whose variables can only be incremented and decremented, and whose only control structure is the while loop. The syntax is designed to be as easy to parse as possible. Here is an example w program. Below I'll describe what it does.

a+ a+ a+
b+ b+

There is a preprocessor [to be provided] that, among other things, standardises the whitespace, so that the code above will be formatted like this:

a b
a+ a+ a+ b+ b+ a{ a- b+ }

The first line (provided by the preprocessor) is a list of all the variable names that appear in the program. All variables in w are unsigned infinite-precision integers. (Infinite precision means that they will never overflow. This is very important for Turing-completeness.) A variable name is any combination of the characters a-z, A-Z, 0-9 and _. All variables initially hold the value 0.

The second line is a list of expressions. There are three kinds of expression. The first two are <variablename>+, which increments a variable by 1, and <variablename>-, which decrements it by 1. (For C programmers, think of these as the postfix ++ and -- operators.) Since the variables are unsigned, it is an error to decrement a variable whose value is zero. This will halt the program immediately. (Note that errors are counted as halting for the sake of this challenge.)

The third type of expression is a while loop. Its syntax takes the form {<variable_name>,<expression_list>}. If the variable has value 0, the expression list is skipped. Otherwise, the expression list is executed repeatedly until the variable becomes zero. (If the variable never becomes zero, the program fails to halt.) That's it - there's nothing more to the language than that.

Note that if you split the second line of the preprocessed program at the spaces, each item will either be } or a variable name followed by a symbol, so you can easily pop off the last character to see what kind of expression you're dealing with.

Looking back at the example program, the first line, a+ a+ a+ increments a three times, setting it equal to 3, and the second line sets b to three. The while loop decrements a while incrementing b until a is zero. So the value of a is added to b, and at the end of the program, a is zero and b is equal to five.

Alternative syntax

Optionally, the preprocessor can output w programs as a string representing a Python list. The example program would appear as follows. The first sublist is the list of variables, and the second is a list of lists representing the parse tree.

[["a", "b"], ["a+", "a+", "a+", "b+", "b+", "a{", ["a-", "b+"]]]

Input and output

For the sake of this challenge, we only care whether a program halts or not when given no input, so there is no input or output in the w language as described here. However, if we wanted we could say that a special variable (let's say _) is initialised with the program's input, and the value of the last expression evaluated is the output. If we do this, the language becomes Turing complete in the classical sense. (The proof is left as an exercise to the reader.)

Implementation notes

Implementing W correctly requires the use of infinite-precision integers. However, the only operations these need to support are incrementing and decrementing, which makes them much easier to implement. The reference implementation uses Python's unlimited precision integers.

| |
  • \$\begingroup\$ As written this seems to allow P to fail to halt if the supplied program fails to halt. "Completely define its syntax and semantics" could lead to disputes, especially if someone chooses to use an obscure semantic model or to define their L in terms of an existing language which doesn't have formally defined semantics. \$\endgroup\$ – Peter Taylor Oct 26 '14 at 8:16
  • \$\begingroup\$ I think this will be way too hard on the side of the cops to be feasible for PPCG. \$\endgroup\$ – Martin Ender Oct 26 '14 at 10:53
  • \$\begingroup\$ @PeterTaylor I've fixed the first of those issues - do you have an intuition on how to deal with the second? \$\endgroup\$ – Nathaniel Oct 26 '14 at 13:38
  • \$\begingroup\$ @MartinBüttner I like hard challenges, and by posting them I hope to attract other users who feel the same way. I think "this challenge is too hard" is not a thing that should be said here; it might seem hard to some people (especially before a solution has been posted) but one shouldn't underestimate how clever people can be. I'm not sure but I think being hard for the cops rather than the robbers is a good thing in this type of challenge. \$\endgroup\$ – Nathaniel Oct 26 '14 at 13:40
  • \$\begingroup\$ I see this as much too easy for the cops, who can simply use a tedious integer factorization or similar task as always. Define L as follows: after performing trial division on a hard-coded integer, execute a Brainfuck program if it has a 200-digit prime factor, terminate without executing those instructions if it has a 201-digit prime factor, or otherwise go into an infinite loop. P simply prints 1. \$\endgroup\$ – feersum Oct 26 '14 at 15:30
  • \$\begingroup\$ Not really. You could pick a semantic model and require people to use it, but then you exclude people who don't know it and don't want to learn it just for this challenge. You could pick an L and require everyone to use it, but I expect you to say that that would take away a lot of the fun. \$\endgroup\$ – Peter Taylor Oct 26 '14 at 17:40
  • \$\begingroup\$ @feersum ah, you're right, this challenge can be gamed in that way. Even worse, you could use something like the twin primes conjecture instead of prime factorisation, and nobody could crack your entry without collecting a Fields medal. I'm not sure if there's a way to fix that :( \$\endgroup\$ – Nathaniel Oct 27 '14 at 0:36
  • \$\begingroup\$ @PeterTaylor I'd be quite happy to pick an L for everyone - that would also solve the problem feersum pointed out - but the question is, what should it be? It needs to be Turing complete and simple enough to analyse programmatically, and I guess it would help a lot if it was also fairly human-readable and intuitive. (That pretty much rules out lambda calculus, which is the obvious choice, though it's actually already a bit fiddly to deal with lambda expressions programmatically because of having to track free variables and do alpha-conversions all the time.) Do you have any thoughts? \$\endgroup\$ – Nathaniel Oct 27 '14 at 0:55
  • \$\begingroup\$ If you want to take a functional approach then pick a universal set of combinators (e.g. SK or Iota). If you want an imperative language, either a well-specified BF or a "toy" language like IMP (as in the one described in Winskel's book on semantics, not the one described in the Wikipedia page - which might confuse people too much). Or pick something interesting from esolangs.org. \$\endgroup\$ – Peter Taylor Oct 27 '14 at 12:16
  • \$\begingroup\$ @PeterTaylor in case you're interested, I invented my own Turing-complete language (imperative but much more minimal and easier to parse than IMP) and added its spec to the draft. \$\endgroup\$ – Nathaniel Oct 29 '14 at 10:27
  • \$\begingroup\$ Looks like a restricted form of Minsky register machine. As a fan of MRMs, I approve. \$\endgroup\$ – Peter Taylor Oct 29 '14 at 10:35
  • \$\begingroup\$ @PeterTaylor yes, indeed, that's what I based it on. \$\endgroup\$ – Nathaniel Oct 29 '14 at 10:36
  • \$\begingroup\$ A potential loophole for cops: The cops' program searches for a string that has a certain hash. If the string's length is more than 400, it outputs true, otherwise it outputs false. It would be very difficult for the cops to prove that the program generates an incorrect result. \$\endgroup\$ – Esolanging Fruit May 29 '17 at 21:59
  • \$\begingroup\$ In the non-preprocessed program, what whitespace is necessary? Is a+a+a+b+b+a{a-b+} valid? \$\endgroup\$ – wastl May 24 '18 at 14:05
  • 1
    \$\begingroup\$ @wastl not sure if I'll ever post this, but the preprocessor would ignore all whitespace, so that would be fine \$\endgroup\$ – Nathaniel May 25 '18 at 0:31

King Me - Draughts King of the Hill

Note: I made this CW so someone else can take it over, because I have no desire to make the controller and run the tournament anymore.

Draughts (or checkers, as it is known in the United States) is a well-known international game. I was surprised that we have not had a draughts King of the Hill yet, so here's one! In case you're unfamiliar with the rules (or perhaps you need a refresher), here are the rules for English draughts, the version we will be playing.

Draughts is played on a checkerboard that looks like this:

draughts board

There are two players, white and red, who sit on the side of the board closest to their pieces' starting position. White moves first. Normal pieces (men) may move forward (from the perspective of the player; towards the other player) one space along diagonals, or jump over diagonally-adjacent pieces that are in front of them to capture them and remove them from the game. Because pieces can only move diagonally, they will always be on the dark squares of the board.

For example, the following move is permitted, and would result in the red piece being captured:


Players may jump as many pieces in a row as possible when making their move, which results in all jumped pieces being removed. Normally in draughts, jumping is not optional - if you can jump, you must jump, and you must make the longest jump possible. However, for this game, jumping is optional, and you do not have to make the longest jump possible if you do not wish to.

Additionally, when a man reaches the furthest row (the row closest to their opponent), it is promoted to a "king", which confers the ability to move (and capture) backwards along diagonals.

A game is ended when a player's pieces have all been captured or the player cannot make a valid move. The player who cannot move due to being trapped or having no pieces is the loser. To prevent games from going indefinitely, I am adding the additional condition that, if a capture has not happened in 10 turns (a turn being defined as ending after the red player has made their move), the game is ended and declared a draw.

The Tournament

Submissions will be accepted for seven days following the posting of this question. At 11:59 PM UTC on the seventh day, registration will close, and the tournament will be run soon after.

Submissions will compete in a round-robin tournament. 5 points will be awarded for a win, 2 points for a draw, and 0 points for a loss. 10 games will be played per match, for each pair of contestants. The submission with the highest score at the end of the tournament will be declared the winner and chosen as the accepted answer. In the event of a tie, total number of wins will be used to decide the winner.

If a bot makes an invalid move or takes longer than 1 second (judged using Java's Timer class), it will be ruled as a forfeit for that game.

To make things simple for me, all submissions must be in Java, and will be classes that inherit from a common Bot interface. The Bot code and Controller class are provided below:

[todo: bot and controller code]

  • 2
    \$\begingroup\$ Maybe as a note you should put that Draughts (Checkers) has been solved, and is in fact the largest game to ever be solved: en.wikipedia.org/wiki/Solved_game#Solved_games \$\endgroup\$ – geokavel Nov 15 '15 at 16:38
  • \$\begingroup\$ @geokavel Good point. Since it has only been weakly solved (meaning perfect play can only prevent a loss, rather than force a win), I'm going to compensate for that by increasing the number of points for a win. That should incentivize players to go for wins, rather than forcing draws. \$\endgroup\$ – user45941 Nov 15 '15 at 16:43
  • \$\begingroup\$ I still think that the bot that plays perfectly (no loss) will end up the winner of this KoTH, unless you make the win points really high (like 10), so that 1 win amounts to 5 draws. \$\endgroup\$ – Nathan Merrill Nov 15 '15 at 16:52
  • \$\begingroup\$ @NathanMerrill I want to incentivize winning, but not to the point where perfect play is disincentivized. The winning bot should be one that uses perfect play to avoid losses, but deviates to try to force wins when it can. Besides, the end-game conditions are different here from the style that was solved, so perfect play may not be so perfect here. \$\endgroup\$ – user45941 Nov 15 '15 at 17:01
  • 1
    \$\begingroup\$ @Mego: I don't think that is what "weakly solved" means. The game if played perfectly results in a draw. It is weakly solved because some positions were proven suboptimal. As a result traversing those parts of the game tree never happened. A computer cannot play this game perfectly as a human could decide to take a suboptimal path but the computer would have no idea what to do. Strongly solving means (roughly) a computer knows what to do at every point. \$\endgroup\$ – Dair Oct 21 '16 at 22:02
  • \$\begingroup\$ Do you intend to post this at some point? I might be interested to write a challenge and a language-agnostic controller (using STDIO and/or argv for I/O), but apparently you and another user have both created a sandbox post on the same topic. \$\endgroup\$ – PurkkaKoodari May 25 '18 at 23:52
  • \$\begingroup\$ @Pietu1998 I posted this in the Secret Santa's Sandbox post a while back - it's fair game for anyone who wants to complete it. \$\endgroup\$ – user45941 May 26 '18 at 6:46

Count the cubes

Here is a picture of a diamond tiling shamelessly stolen from Random ASCII Art of the Day #5: Diamond Tilings:

However it also has the property of representing a 3D isometric view of a 5×5×5 cube with 59 cubes removed, leaving 66 behind. (Cubes obscured by other cubes are assumed to exist.)

Your task is, given an ASCII art representation of a diamond tiling, is to output both the number of cubes removed and remaining. For example (some shamelessly stolen from Scale up a Diamond Tiling):

 /   /\
/___/  \ -> 1 0 or 0 1
\   \  /
 /   /\   \
/___/  \___\ -> 1 1
\   \  /   /
 /   /\   \   \
/___/  \___\___\ -> 2 1 or 1 2
\   \  /   /   /
 /   /\   \   \   \
/___/  \___\___\___\ -> 3 1 or 1 3
\   \  /   /   /   /
 /\   \   \
/  \___\___\
\  /   /\   \
 \/___/  \___\ -> 3 1 or 1 3
  \   \  /   /
   /   /\   \
  /___/  \___\ -> 3 1 or 1 3
 /\   \  /   /
/  \___\/___/
\  /   /   /
   /   /\
  /___/  \
 /\   \  /\
/  \___\/  \ -> 3 1 or 1 3
\  /   /\  /
 \/___/  \/
  \   \  /
   /   /\   \
  /___/  \___\
 /\   \  /   /\
/  \___\/___/  \ -> 4 4
\  /   /\   \  /
 \/___/  \___\/
  \   \  /   /
     /   /   /\   \
    /___/___/  \___\
   /   /\   \  /\   \
  /___/  \___\/  \___\
 /\   \  /   /\  /   /\
/  \___\/___/  \/___/  \ -> 16 11 or 11 16
\  /   /\   \  /   /\  /
 \/___/  \___\/___/  \/
  \   \  /   /\   \  /
   \___\/___/  \___\/
    \   \   \  /   /
     /   /\   \   \   \   \
    /___/  \___\___\___\___\
   /\   \  /\   \   \   \   \
  /  \___\/  \___\___\___\___\
 /\  /   /\  /   /   /   /\   \
/  \/___/  \/___/___/___/  \___\
\  /\   \  /   /\   \   \  /   /\
 \/  \___\/___/  \___\___\/___/  \ -> 40 20 or 20 40
  \  /   /\   \  /   /\   \   \  /
   \/___/  \___\/___/  \___\___\/
    \   \  /   /\   \  /   /   /
     \___\/___/  \___\/___/___/
      \   \   \  /   /   /   /
       /   /\   \   \   \
      /___/  \___\___\___\
     /\   \  /\   \   \   \
    /  \___\/  \___\___\___\
   /\  /   /\  /   /   /\   \
  /  \/___/  \/___/___/  \___\
 /\  /\   \  /   /   /\  /\   \
/  \/  \___\/___/___/  \/  \___\ -> 46 18 or 18 46
\  /\  /   /\   \   \  /\  /   /
 \/  \/___/  \___\___\/  \/___/
  \  /\   \  /   /\   \  /   /
   \/  \___\/___/  \___\/___/
    \  /\   \   \  /   /   /
     \/  \___\___\/___/___/
      \  /   /   /   /   /

The output can be in any reasonable format, e.g. an array return value or a string with whitespace, but it must contains both values, even if they are the same, however the order of the two values does not matter in any way; you could even reverse the order on subsequent runs if you wanted to.

This is , so the shortest solution wins!

| |
  • \$\begingroup\$ One more maybe? Also meta.codegolf.stackexchange.com/a/8101/8478 ... I'd just put all test cases in one code block and the result for each on the next line. \$\endgroup\$ – Martin Ender Feb 27 '16 at 17:41
  • 2
    \$\begingroup\$ Much better. I'd still put the results of the test cases on the next line though to make it easier to process them all automatically. \$\endgroup\$ – Martin Ender Feb 28 '16 at 15:56

Ant Wars

Parts of this challenge are based off of Ant Queen of the Hill Contest.


Your objective is to conquer the ants of the world ... or have the biggest army of ants. To do this, you start with a single queen. The queen can create worker ants by using food gathered by itself or other worker ants. Your worker ants can kill other ants by attacking them. You win if you have the only queen left, or if you have the biggest army of ants.


The board will be a square with wraparound borders. The length of each edge is determined by sqrt(1000*n)1. Before the game fierce battle for domination starts, 100*n pieces of food will be distributed semi-randomly on the board . n queens, 1 for each player, will also be randomly distributed on the board.

1: n is the number of starting players


Sight and Smell

Ants are usually near-sighted and have somewhat short antenna. Because of this, ants in this simulation can only see and smell ants, food, and pheromone in its 3 by 3 neighborhood. They can also tell the difference between ants of different species.


Because of limited brain space, every ant has a memory of up to 5 characters long. The starting memory for queens is 5 spaces.


Every ant is oriented in the direction that it last moved. Queens start out oriented in a random direction.


Each worker ants can carry up to 1 unit of food. A queen ant can carry an unlimited amount (so that's what her body is for). Every ant picks up as much food on its current square as possible. A queen ant takes all the food from adjacent squares including that carried by workers of any player.


Every turn, every ant is given a view of the local surroundings and then decides to move. Ants are given priority in their movement with those that are oldest moving first. The initial order for the starting queens is random.


An ant attacks by attempting to move onto another ant. Worker ants require two ants attacking them in order to be killed. Queen ants require eight ants attacking it in order to be killed. Queen ants cannot attack. An ant after being killed drops all food it is carrying and one additional unit of food.


An ant can move to any of the 8 surrounding squares. This changes the orientation of the ant to the direction it is moving. If it tries to move to a square with an ant already on it, it is assumed to be attacking that ant, no matter if friendly or not.

Dropping Pheromone

An ant can optionally increase the value of 4 different pheromones on the cell it is on, 1 of which can only be seen by ants of that particular colony. Pheromone has a value of a double-precision float and decreases by 1% every game tick. An ant can increase pheromone by up to 10.

Creating Workers

A queen ant may create a worker and spawn it in any of the surrounding cells. The queen ant also chooses the memory of the new worker.


A game ends after there is only one queen left or after 10000 turns. The winner is one of the players with a queen with the most workers. I will determine the winner after playing a number of games ... depending on the amount of time it takes to play each game.


You can implement a program or a java class that takes in an ant input and gives an ant output for that ant.


Input contains your player id, your ant's memory, if your ant is a queen, and then the contents of the cells surrounding it. The cells are given from the top left to the top right in this order:

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

Input is format thus:


Cell info is formated like this:


player_id and ant_owner are positive integers.
ant_memory is a 5-character long string.
is_queen is one of true or false.
The pheromones are double-precision (64-bit) floats.
ant_type is one of W (for worker ants) and Q (for queen ants).
If there is no ant on a cell, ant_type and ant_owner will be omitted from the input.


You have to output the cell you want to move to, the pheromone you wish to add to your current cell, and whether the ant would like to create an ant instead of moving (only works for queens :P).

It should be formatted thus: next_memory;cell;pheromone_0;pheromone_1;pheromone_2;pheromone_3;create_ant;created_ants_memory

The controller is rather flexible and should be able to understand what you write if you use different delimiters or leave out some of the information. Make sure that next_memory comes first in your programs output and that it is exactly 5 characters long. If creating an ant, created_ants_memory needs to be the last 5 characters in the input.

cell has to be an integer in the range [0, 8] (defaults to 4).
pheromone_n has to be a positive float (defaults to 0).
create_ant needs to be one of: true, false, yes, no, 1, or 0 (defaults to false).

How to create a bot:

You have 3 options for this. You can:

  1. Implement the Ant interface with a java class. (Very fast)
  2. Communicate to the controller via I/O streams. (Fast (I think))
  3. Be called via command arguments and output via STDOUT (Slow depending on OS and programming language)

Note: Your bot must be completely deterministic. Given the same input, your bot should always return the same output.

Method 1:

Ant interface:

interface Ant {
    String move(String input);

Implement this interface for your ants :)

Method 2:

Every time it is one of your ants' turns, your program will receive a line of input through STDIN followed by a newline. After receiving the input, your program is expected to output a line through STDOUT followed by a newline.

Method 3:

Your program will be executed with the input line as its first argument. Your program is expected to output through STDOUT.

Time limit

Each time your program is called, it should return within 5 milliseconds. Since the time limit may be exceeded due to fluctuations outside your control, an average will be calculated. If at any point the average is above 5 milliseconds and the total time taken by your program across all calls so far is more than 10 seconds, the relevant player will be disqualified. This means they will not be eligible to win, their ant function will not be called again during that game, and all ants of that player will instantaneously perish.


  1. How can I improve this to look prettier?
  2. Any typos or formatting issues?
  3. Any other ways I can improve this challenge?
| |
  • \$\begingroup\$ What is n? Where do queens start? Go through everything as if you were writing the underlying code, and ask yourself "How would that be implemented?". It's a good way of making sure all the info is in there. \$\endgroup\$ – wizzwizz4 Jan 3 '16 at 15:41
  • \$\begingroup\$ @TheNumberOne Could you put a link to / embed the controller? Or perhaps post this as an actual challenge? \$\endgroup\$ – wizzwizz4 Jan 3 '16 at 19:45
  • \$\begingroup\$ @trichoplax Answered your questions in the post... though I am a little late :P \$\endgroup\$ – TheNumberOne Mar 15 '16 at 20:45
  • \$\begingroup\$ @BentNeeHumor Good to see we are both working at the same rate :) \$\endgroup\$ – trichoplax Mar 16 '16 at 9:54
  • 1
    \$\begingroup\$ In chatting about my ant KotH in the dedicated chat room I remembered this version with pheremones that fade over time. I'd love to see this posted to main. Is there anything that needs to be addressed or anything we can help with? \$\endgroup\$ – trichoplax Jan 13 '18 at 20:45
  • \$\begingroup\$ (P.S. In case you hadn't seen it, mine finally made it to main after 2 years in the sandbox, back in July) \$\endgroup\$ – trichoplax Jan 13 '18 at 20:46
  • \$\begingroup\$ define "character" - is the memory ASCII-only? \00-\ff? any unicode character? \$\endgroup\$ – dzaima Jan 13 '18 at 21:31
  • \$\begingroup\$ @trichoplax sorry, I haven't been active on here for a while. you can probably do whatever with it ;) \$\endgroup\$ – TheNumberOne Jan 13 '18 at 23:43

King of the Sausage

This is just a draft.

I saw this (slightly altered) 'game' in a tv show once: Two competitors are each given a sausage of equal weight. Then they each have to cut pieces from this sausage (without seeing how much the oponent cut off) which then are weighted against each other. The player that has the heavier piece gets a point. Then the weighted sausage pieces are discarted and the process is repeated. After 5 rounds the one who got the heavier piece more often wins.

A win results in 3 points, a loss in 0, a tie in 1 for.


Here the saussage weight is given as an integer totalWeight. You can only cut off pieces of integer size.

Each submission should write a JavaScript function that takes these arguments:

  • totalWeight: The units of the total weight of the sausage at the beginning as an integer between 5 and 2^31-1.
  • round: An integer between 0 and 4 that indicates the current round.
  • ownPieces: An array of size 0 upto 4, each element is the size of the piece you cut of in the previous round.
  • opponentPieces: The same, but with the pieces of the oponent.
  • memory: A variable that allows you to store information between the rounds. It can contain any kind of structure. It is initialized with 0 before the first game with an new oponent and it can store information between those games.

Each time it is called, it has to return an integer between 0 and the weight of the remaining sausage (= totalWeight minus the sum of the entries in ownPieces). If it does return anything else, the submission will be disqualified. The function may not access any global variables and may not try to influece the game in any other way. It cannot take more than 100ms per round.

Each pair of oponents will play this game a certain number (to be determined ) of times against each other.

Feel free to share your thoughts / suggestions!


How should the initial sausage weight be determined?

Possible controller inspiration: https://jsfiddle.net/CalvinsHobbies/ave6ejyd/

| |
  • \$\begingroup\$ Are the weights integers or floats? \$\endgroup\$ – Peter Taylor Oct 24 '15 at 10:06
  • \$\begingroup\$ That is a crucial point thanks! The original game would obviously lead to using floats, but now that you ask, I think the integer problem would be even more interesting, don't you think? \$\endgroup\$ – flawr Oct 24 '15 at 11:31
  • \$\begingroup\$ I think using integers is good because it avoids discrepancies over parsing and rounding, but using small integers would allow a lot of pre-analysis to be done. I suggest starting at a random integer between 1000000000 and 2000000000 (within the range of signed 32-bit ints, but too large and variable to be easily pre-analysed). Oh, and if both run out of sausage then the remaining rounds should be ties. Allow a match to be tied, and score 3 points for a win and 1 point for a tie. \$\endgroup\$ – Peter Taylor Oct 24 '15 at 12:53
  • \$\begingroup\$ The clearest thing to me when competitors have no sausage is for them to tie the remaining rounds. I'm not sure if there is some other constraint you are thinking of, though. I also think I like Peter's idea of using a slightly random but guaranteed to be large sausage instead of a constant one. I don't think you would have any real problems given the size, but I think it would highlight the more interesting parts of the challenge. \$\endgroup\$ – FryAmTheEggman Jul 4 '16 at 14:29
  • \$\begingroup\$ If we have a variable saussage size, does anything prevent us to also throw in small numbers (at least the number of rounds)? As the competitors do not exactly know what numbers there will be, it seems it does not matter? \$\endgroup\$ – flawr Jul 4 '16 at 19:07

Simulate Colorblindness

As some of you might know, I am colorblind. Specifically, I have moderate deuteranopia. This means that I have difficulty distinguishing between red, green, and yellow colors, as well as various shades of purple and blue, due to not having green cones in my eyes.

The most common way to diagnose colorblindness is through the use of the Ishihara test. In this test, various image plates are shown to the individual. These plates are comprised of dots of several shades of the same color, where certain shades are grouped together to form numbers. The shades are chosen so that, based on the set of plates on which the individual fails to recognize the number, the type of colorblindess can be determined.

Here are a few samples of Ishihara plates:

plate 1

This plate (plate #1 in the Ishihara 24-plate test) is a control plate - everyone should be able to see the number 12 clearly, regardless of whether or not they are colorblind. This is the only plate on which an individual with total colorblindness (monochromacy) can read the number.

plate 2

This plate (plate #2) has an 8 inscribed on it, but individuals with red-green deficiencies see it as a 3 (myself included).

plate 8

This plate (plate #8) has a 6 inscribed on it, but individuals with any type of colorblindness cannot see any number.

plate 14

This plate (plate #14) will be seen as having a 5 on it by individuals with red-green deficiencies, but others will not see any number.

plate 16

This plate (plate #16) has the number 26 on it. Individuals with protanopia will only see the 6, and individuals with deuteranopia will only see the 2.

The Challenge

Given a set of Ishihara plates, output the number that an individual with each type of colorblindness (none, protanopia, deuteranopia, and monochromacy)1 would see on the plate. Your score will be the number of correct outputs your program gives for each plate in the scoring battery (up to 4 points per plate).

For testing purposes, here is an Imgur gallery containing the first 17 original Ishihara plates. The correct outputs for each plate are as follows:

X means that no number can be read
Plate #: Normal, Protanopia, Deuteranopia, Monochromacy
1: 12, 12, 12, 12
2: 8, 3, 3, X
3: 29, 70, 70, X
4: 5, 2, 2, X
5: 3, 5, 5, X
6: 15, 17, 17, X
7: 74, 21, 21, X
8: 6, X, X, X
9: 45, X, X, X
10: 5, X, X, X
11: 7, X, X, X
12: 16, X, X, X
13: 73, X, X, X
14: X, 5, 5, X
15: X, 45, 45, X
16: 26, 6, 2, X
17: 42, 2, 4, X

The scoring battery will be a unique set of Ishihara plates, created for the purpose of this challenge.


  • Input and output may be in any reasonable manner and format, so long as no extra information (such as the number that should be seen on the plate) is conveyed in the input other than the image data.
  • Builtins which trivialize this challenge (such as an optical character recognizition library like Tesseract) are forbidden. Though I highly doubt that any programming language or library has this functionality built-in, Mathematica and its ilk continue to surprise me.
  • The scoring set of plates will not be disclosed, to prevent optimizing for that specific set.

1: There are actually a few other variations of colorblindess, but Ishihara plates are not effective at diagnosing them.

Sandbox Questions

  • Did I mess up any of the plate images? Being colorblind myself, picking out the proper plate images is rather difficult.
  • Is there anything that needs further specification?
| |
  • 1
    \$\begingroup\$ 1. There seems to be a reference to a footnote, but I don't see the footnote. 2. The descriptions of the plates seem to me ("normal") to match the images. 3. You do realise that the golfiest approach is likely to be to find a single pixel which differs in all the images in the test battery? I'd be rather surprised if any answer actually does OCR. \$\endgroup\$ – Peter Taylor Aug 24 '16 at 10:03
  • \$\begingroup\$ @PeterTaylor Thank you for reminding me to add the footnote. As for point 3, disallowing optimizing for the scoring cases takes care of that. \$\endgroup\$ – user45941 Aug 24 '16 at 10:11
  • 2
    \$\begingroup\$ As usual with those kinds of classification challenge, the optimal way to provide data should be: a training set, a validation set, and a test set. You only provide the training and validation set, so that people can use the training set to build their algorithms and the validation set to check that they generalize properly. You keep the test set to yourself and use it to give a score to each answer, as such no one can optimize their algorithm to get the best score. \$\endgroup\$ – Fatalize Aug 24 '16 at 12:03
  • \$\begingroup\$ I agree with Fatalize regarding the hidden test set. Also, that plate #14 is blowing my mind (since I have no problems with vision, I've never experienced the "other" side of these sorts of tests). \$\endgroup\$ – AdmBorkBork Aug 24 '16 at 15:32
  • \$\begingroup\$ @Fatalize I wasn't sure about how people felt about the scoring set not being public, but I will go along with that suggestion. \$\endgroup\$ – user45941 Aug 24 '16 at 21:02

Natural Pi - The Front Nine W.I.P.

## Meta ## 
    - 4 more ways to calculate pi with nature?


These challenges are simulations of algorithms that only require nature and your brain (and maybe some re-usable resources) to approximate Pi. If you really need Pi during the zombie apocalypse, these methods don't waste ammo! There are nine challenges total.

Each challenge will give an algorithm for approximating Pi with nature. Then it will walk through how the computer simulation should work. Next comes the Specification to clear up details and finally there are some test cases.

Natural Pi #0 - Rock

  • Coprime Probability

Natural Pi #1 - Sand

  • Buffon's Needle

Natural Pi #2 - River

  • Curvy-ness of a River

Natural Pi #3 - Books

  • E's in a circle

Natural Pi #4 - Sun Flower

  • Ratio of Area to Diameter

Natural Pi #5 - Vine

  • Period of a Pendulum

Natural Pi #6 - Fire

  • Ratio of Circumference to Diameter

| |
  • 1
    \$\begingroup\$ Please read meta.codegolf.stackexchange.com/a/8464/45941 \$\endgroup\$ – user45941 Sep 8 '16 at 21:30
  • \$\begingroup\$ @Mego my intention is to post these as distinct challenges and not a multipart challenge. \$\endgroup\$ – NonlinearFruit Sep 8 '16 at 21:54
  • \$\begingroup\$ Then why is the multiple-holes tag present? \$\endgroup\$ – user45941 Sep 8 '16 at 21:57
  • \$\begingroup\$ @Mego Oops, thanks for pointing that out \$\endgroup\$ – NonlinearFruit Sep 9 '16 at 1:19
  • 3
    \$\begingroup\$ The "probability that two random integers are relatively prime" isn't well defined. You can't talk about a "random integer" without defining a probability distribution, and you can't uniformly select a random integer because there's an infinite number of them. \$\endgroup\$ – Peter Taylor Sep 13 '16 at 14:16
  • \$\begingroup\$ @PeterTaylor Good catch, I have specified an interval for the random numbers \$\endgroup\$ – NonlinearFruit Sep 13 '16 at 21:18
  • 2
    \$\begingroup\$ Reusing sandbox posts like this doesn't really work. There are already 2988 answers in the sandbox: it won't harm to have one more, and it means that the new question can be commented on, voted ready, etc. independently of the previous one. \$\endgroup\$ – Peter Taylor Sep 22 '16 at 20:42
  • 1
    \$\begingroup\$ @PeterTaylor Good point, I was originally tracking my ideas and hoping for recommendations on the set as a whole, but I'll migrate this to individual posts, \$\endgroup\$ – NonlinearFruit Sep 26 '16 at 23:16

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

The Best Way to Rake Leaves

[This is just a little problem I thought up while doing yard work today. It is not fully specified and I may not finish it if some simple optimal solution is found.]

Suppose some 2D grid represents the area of a lawn. A number of leaves are strewn over the lawn and they are modeled as single grid points. You have a rake that is modeled as a line segment of length L.


To start you can rotate the rake in any way and put it anywhere on the grid.

When the rake is moved some distance d along its perpendicular, all the leaves in its path are caught in it. They stay on the rake line until the rake stops (as with normal raking).

You repeat this process (moving the rake different distances every time) until all the leaves all lie on one singular point.

The question is: what is the minimum distance the rake has to move to make this happen?
(i.e. what is the minimum sum of the d's from each move?)

Challenge Spec (details incomplete)

Write a program that takes in a list of (x, y) leaf points and the length L of the rake (all floats).

The program should output a sequence of rake moves in the form of ((x1, y1), (x2, y2)) line segments that the rake travels perpendicularly down the center of. This sequence must bring all the leaves to the same exact point when they are "moved" by the rake

The challenge is to make an algorithm that does this with the least possible sum of sqrt((x1-x2)^2 + (y1-y2)^2) over all points.

[At this point several test cases would be given, with different L values and different leaf distributions. The submission that minimizes the total distance wins (assuming they do not hard code the answer).]

[This optimization problem does not seem to have any trivial solutions or even a clear optimal solution. Can anyone else poke holes in it?]

| |
  • \$\begingroup\$ I still think this would be a fairly interesting problem. Any plans of still posting it at some point? \$\endgroup\$ – Martin Ender Dec 12 '14 at 22:49
  • \$\begingroup\$ @MartinBüttner Yes, I have been trying to get around to it. If I don't in a week or so feel free to post it yourself. \$\endgroup\$ – Calvin's Hobbies Dec 13 '14 at 6:15
  • \$\begingroup\$ No rush. I'd probably rather try to participate than post it myself. ;) I am considering posting something related though (it wouldn't be an optimisation problem, but it might be reusable as a substep for this challenge, although I'm not even sure it's anywhere near an optimal approach to this). \$\endgroup\$ – Martin Ender Dec 13 '14 at 12:03
  • \$\begingroup\$ @programmer5000 Adopt it. That's fine. \$\endgroup\$ – Calvin's Hobbies Jun 9 '17 at 20:04

Tower Builder

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

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

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

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

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

The Formic Forest - Ant QotH Contest


While the ants of the highlands gather food and walk around each other, their distant cousins live in the forests below, growing fungus and aggressively raiding the ground and other nests for food. But like their highland counterparts, they want food, and they have armies of workers at their disposal to get at it.

The Arena

The arena is a torodial 1000*2500 rectangular grid of cells. Each cell has one of eight colors, and at most one object at any one time. There are three types of objects of significance:

  • Ants are either queens, which are spawned at the start of the game, or workers, which are spawned by queens.
  • Food is a prized possession, and may be hoarded or consumed.
  • Fungi are ant-placed objects which may be created at low cost and will grow slowly into food if left alone within the vicinity of food.

In this game, adjacency refers to being in the Moore Neighborhood unless otherwise specified. Some rules instead specify the von Neumann neighborhood.

Game Overview

Each game, 16 submissions are put against each other in a game. If the competition has fewer than 16 submissions, all of them participate in a game, and if there are more, the 16 players are chosen randomly.

At the beginning of each game, each cell is reset to the color 0 (white), each submission used in the game has its corresponding submission object constructed, and 2500 food, and 16 queens are randomly scattered onto the map. Queens are very unlikely to be adjacent to food or other queens, but this is not a guarantee.

Then the game itself proceeds. The game lasts for 15000 turns, and each turn consists of the following phases, each of which is resolved concurrently in turn:

  • Decide: Each ant's views are determined based on the current state of the arena and previous move history, and each ant's decision is determined and validated separately.
  • Move: Each ant's decision is executed simultaneously, and the presence of multiple objects in a single cell resolved once all ants that decided to move into a cell have done so.
  • Grow: Each object that can potentially change as a result of its surroundings has its neighborhood resolved, and the changes to the objects as a result happen simultaneously.

After the 15000 turns is up, the game ends. Submission objects are disposed of, caches trimmed down, food amounts logged, and the process started again if more scores need to be collected.

Ant Senses

Each ant has a 5*5 area of sight centered on themselves. This area of sight is arranged to give the ants a relative sense of direction in the immediate term, but not innately in the long term. Ants can see the color of empty cells, and the properties of objects in filled cells, but not the color of filled cells.

Each ant also has an internal state that can take one of eight values. This state is internal to that ant, and to transfer information between herself and other ants or to remember more than this, she must position herself, drop payloads, or mark the ground below her, all which are subject to enemy interference.

Ant Actions

Using their senses, ants can decide to move or drop payloads, and also color their current cell and change their current state simultaneously, once per turn. The coloring happens on the cell that the ant is currently in, before she moves.

Ants move orthogonally or diagonally one cell at a time. Worker ants are free to move into other cells at their own risk, but a queen may not move to a cell that her view shows is in the Moore neighborhood of a non-adjacent queen, nor to a cell that her view shows is in the von Neumann neighborhood of an adjacent queen. (However, it is legal for a queen to stay still on a cell adjacent to another queen.) Additionally, a queen without food may not move into a step into a cell already occupied by a laden worker, lest she step onto a laden worker that decides to stay still, which would without this restriction kill her.

Instead of moving, ants may instead drop a payload into an adjacent cell. Food payloads cost one food, and can only be performed if the ant is carrying food. Fungus payloads cost nothing, and may be freely placed. Ant payloads may be performed only by the queen, cost one food, and consistently result in a new loyal worker. It is legal to drop payloads on oneself, but this will usually result in the dropped object being picked back up or destroyed during collision resultion, to no substantive effect.

Ant Lifecycle

Both queen and worker ants start in state 0. Worker ants are oriented such that their "from" cell is the cell the queen occupied when spawning the worker, while queen ants have a random initial orientation. From there, it is up to submissions to perform ant-specific initialization and differentiation if desired.

Once spawned, ants have an indefinite lifetime. Queen ants are guaranteed to live up to the end of the game, but worker ants may die by colliding with other ants.

Ant Leeching

After movements and collisions are handled, a queen may neighbor one or more unladen enemy workers. If the number of such neighbors is equal to or less than the amount of food carried by that ant, then the queen loses food equal to the number of adjacent enemy workers. An unladen worker ant that neighbors one or more enemy queens that lose food this way gains one food. If a worker is next to multiple such enemy queens, she receives only one food, and one or more food is simply lost forever.

This transfer does not occur between allied ants. To perform such food transfers, you must command the laden ant to drop her food in an adjacent cell, and have another ally be in that cell to automatically pick it up.


Fungi are a means of spawning more food. Fungus farms may potentially lead to bountiful harvests for submissions that invest the resources to spawn, watch over, guard and harvest these fungi. They may also be strategically planted to obscure the ground or probe for food from a distance.

If food is within a 9 by 9 cell area centered around the fungus, then the fungus will grow. Internally, fungus takes 32768 steps to mature and spawn into food, and will gain 1 step per generation per piece of food placed in this vicinity. Therefore, placing more food in the vicinity of a fungus will speed up the fungus's growth, but will also make a nice feast for any ants that find it. If a fungus is not within the vicinity of food, it will not grow.

Growth stages are visible to all ants, and work as a coarse indicator of the age of the fungus. 0 means that the fungus has taken no steps toward maturity, 1 means the fungus has taken 1-7 steps toward maturity, 2 means the fungus has taken 8-63 steps toward maturity, 3 means the fungus has taken 64-511 steps toward maturity, 4 means the fungus has taken 512-4095 steps toward maturity, and 5 means the fungus has taken 4096-32767 steps toward maturity. (If a fungus completes all 32768 steps of growth, it matures into food in time for ants to see it as food the next turn.)

Collision Resolution

As noted above, all decisions are executed at once, and collisions are resolved as they happen once surrounding ants have all their decisions executed.


Collisions are an unavoidable consequence of multiple ants deciding to enter the same cell independently, or one or more ants entering a cell of an ant that decides not to move from it. Because ants may move only one cell at a time, up to 8 ants can move into the same cell at a time, and may run into an ant standing still in it. Queen-queen collisions are prevented by the rules restricting movement within the vicinity of other queens.

Collisions of ants are resolved depending on the ants involved. For the purposes of collision resolution, an ant is considered moving if and only if she spent her turn moving herself to a different cell. A newly spawned worker is treated like a moving worker.

  • A queen, if involved in a collision, is always the only survivor. She loses one food if she moved to a cell containing a laden worker that stayed still. As stated previously, a queen without food may not move to a cell already occupied by a laden worker, preventing the case where an unladen queen would step on a laden worker staying still.
  • The collision of more than one moving laden ants in a worker-only collision results in all involved workers dying, leaving food behind in the cell.
  • If a still laden worker is in a worker-only collision with no more than one moving laden worker, she survives, but loses her food if there was a moving laden worker in the collision.
  • If a single ant in a worker-only collision held food and she moved, then she alone is the survivor. She loses the food she carried if she moved onto a worker ant that stood still.
  • If none of ants in a worker-only collision held food, then they all die.

Food and Fungi

Fungi do not stack. If multiple fungi are placed into a cell at once, collision resolution proceeds as if only one were placed in. Putting fungus in a cell already containing fungus will destroy the old fungus and create a new one. Fungus is destroyed if it shares its cell with any other object.

A queen ant that stays or moves into a cell will pick up all contained and/or placed food in that cell. However, if a worker does the same, she can only pick up one of these pieces, and the rest are simply lost forever. If no ants are available to pick up the food, then only one food remains in the cell, with the rest lost forever.


Each submission must be a Javascript class, with two methods holding special significance: a constructor, which is called once per game start to initialize each object before eachTurn is ever called, and an eachTurn method, which is called concurrently on all new ant views to determine what to do.

The constructor is given no arguments, while eachTurn is given to arguments, an integer corresponding to the current ant's state, and a 25-length view array.

A possible submission skeleton is as follows:

class MyAnt {

    constructor() {
        //TODO: You fill this in

    eachTurn(state, view) {
        //TODO: You also fill this in



The view array contains objects of the following form:

    contents: Integer representing the contents of the cell, 0 for empty, 1 for food, 2 for fungus, 3 for ant
    details: Object giving details about the cell contents

The details object yields further information about the object in the cell, and for each of the possible cell contents, it has the following forms:

  • Empty Cell:

        color: Integer from 0-7 inclusive representing color of the cell
  • Cell with Food:

    {} // Yes, an empty object
  • Cell with Fungus:

        stage: Integer from 0-5 representing fungus stage, a very coarse indicator of age and time to maturity
  • Cell with Ant:

        queen: Boolean representing whether the ant is a queen
        friend: Boolean representing whether the ant is ally or enemy
        food: Integer representing the current food stores of that ant

Each view object provided represents reflects the true state of a cell in the arena, albeit with incomplete information. The array itself always corresponds to a flattened 5*5 cell area of the arena centered on the ant, rotated 0, 90, 180, or 270 degrees such that:

  • For ants that have moved since spawning, either the cell to the top or to the top left correspond to the cell that the ant was in before the one currently inhabited
  • For worker ants that have not moved since spawning, either the cell to the top or to the top left correspond to the cell that the queen occupied the turn she spawned the worker
  • For queen ants that have not moved since spawning, the orientation is randomly determined at the start of the game and remains until the queen moves

Indices in the view array correspond to cells in english reading order:

 0  1  2  3  4
 5  6  7  8  9
10 11 12 13 14
15 16 17 18 19
20 21 22 23 24

There is no means of getting orientation information definitively either form inside or outside, and it must be inferred by current state and surroundings.


The output expected of the eachTurn method is an object with the following fields:

    cell: (Mandatory) Integer in 0-8 inclusive, representing the cell to move to or to drop a payload to
    spawn: (Optional) If present, 0 for no payload, or 1, 2, or 3 for a payload of food, fungus, or worker, respectively
    state: (Optional) If present, an integer in 0-7 inclusive, representing the state to change to
    color: (Optional) If present, an integer in 0-7 inclusive, representing the color to color the old cell with

The cell is interpreted with the same rotation as the view. Output cells 0-2 correspond to view indices 6-8, output cells 3-5 correspond to view indices 11-13, and output cells 6-8 correspond to view indices 16-18. If you compare this to the index chart above, this is in the same english reading order as the view array provided.

No Side Effects

Submissions may not make state modifications except to themselves, and should take care so that internal state modifications from calls to eachTurn are not visible from outside. Debugging submissions using input and output is allowed, but once submitted as an answer, they are forbidden. Attempting to use input or output in a submission will result in an error and disqualification until edited out.


Submissions are expected to behave deterministically, and the eachTurn function is expected to be pure, returing the same decision object for a given combination of state and view, regardless of how eachTurn was previously called or is currently being called.

Built-in functions may be called, if they are similarly externally pure. Math.abs() is fine, but Date.getTime() is not, for some examples. In particular, you are not allowed to call Math.random(). Supply your own pseudorandom numbers from constants, ant states, and ant views.

Unless you have a good handle on javascript concurrency and are willing to stress-test the code for concurrency bugs, I recommend using well-tested concurrency patterns and performing only idempotent modifications of objects, or avoiding modification in the eachTurn object altogether.

Resource Limits

Each game submission starts with 1 second of reserve time. Each call to the constructor and eachTurn add 1 millisecond to the reserve time, then decrement from the reserve time the time they took to execute. Calls are memoized, and don't count against a submission if they are found in cache. If a submission exhausts its reserve time, it is disqualified.

Submissions are also limited to 64 Megabytes of memory at any one time. Unlike the time limit, this limit is not enforced automatically, but if a submission turns out to consistently hog memory during games it participates in, I will use a memory profiler to determine if this limit is exceeded.

After Submission


To keep tournaments running smoothly, submissions are disqualified if their submission performs an invalid action. Disqualified submissions will be excluded from future games within a tournament after a disqualification, and will be kept out of future tournaments until the problem causing the disqualification is fixed.

The following conditions are detected automatically, and therefore result in disqualification immediately:

  • Exhausting reserve time, as described above
  • Returning an ill-formed or badly typed object from eachTurn
  • Throwing an exception from the constructor or eachTurn
  • Attempting to spawn food or workers with no food
  • Attempting to spawn a worker with another worker
  • Attempting to move a queen too close to another queen
  • Attempting to move an unladen queen to a cell containing a laden worker
  • Performing input/output from submitted answers

It might seem harsh to disqualify for a single wrong move or bug, rather than consider it "no move" or ignoring it, but by insisting on correctness from entries, I can focus my efforts on keeping tournaments running quickly and smoothly. This is not supposed to be an additional challenge, so a reason is given for any disqualification, and an explanation given, with specific input and output given to help solve the disqualifying problem.

Multiple Answers and Editing

You may provide multiple answers, provided that each one stands as a competitor in its own right, does not team up with other submissions, and at least in part is the product of your own substantive effort. You may take advantage of other submissions' weaknesses in an effort to achieve a higher score in comparison. Keep in mind that submissions come in, the chances of running into another particular submission will decrease.

You may also edit your submissions to tune them however you choose. There are no guidelines about whether to create a new post or edit a currently existing post; the choice is yours.

If you make a variation of another submission, remember to differentiate it, and if is derived from someone else's work, remeber to credit your sources.


At the end of a game, submissions are ranked on how much food their queens held at the end of the game. Submissions which score exactly equal to each other simply share the average of the ranks they would have if they scored differently from each other.

Submissions with the highest average rank over a multitude of games win. For this challenge, I will give out working first places from tournaments as scores accumulate enough significance that Dunn's test indicates that there is a single distinct first place with at least 98% confidence.


For questions and extended discussion of this challenge, please use the chat room. Comments on this post are likely to be cleared up from time to time, while chat room text will be kept around permanently.

If you want to contribute to the specification itself, see the github repository hosting the latest changes to this specification, right here.

| |
  • \$\begingroup\$ Chat room for this contest: chat.stackexchange.com/rooms/77728/the-formic-forest \$\endgroup\$ – eaglgenes101 May 18 '18 at 23:53
  • \$\begingroup\$ Part of the complexity is making sure that the queen can't become a wrecking ball, but has clearly-defined restrictions so she can't be disqualified by no fault of her own. Take it from me, there's been more than a bit of arguing about how much the queen can and can't do. \$\endgroup\$ – eaglgenes101 May 21 '18 at 22:13
  • 1
    \$\begingroup\$ Why are submissions a JavaScript class? You have rules about side effects and consistency so why not just make a toy language that must be functionally pure to implement the ants? Since the ants have a very limited view of the world it could easily be done with a fall through pattern matching. This would have the added benefit that people wouldn't need to learn JavaScript to participate, they would need to learn the toy language but IMO the language could be simple enough that it could be completely understood from a short description. \$\endgroup\$ – Wheat Wizard May 22 '18 at 23:24
  • \$\begingroup\$ I'm following the mold of the Formic Functions challenge. Javascript is a familiar language that has had thousands of dollars worth pumped into creating optimized implementations, and while it has its shares of impurities and quirks, it's old and widespread enough that its warts are well-known and well-documented. \$\endgroup\$ – eaglgenes101 May 22 '18 at 23:41
  • \$\begingroup\$ @HatWizard If you have any suggestion you can make one, and then someone else may write a JS interpreter of that language. Or this... well, almost all of those are esolang, nevermind. \$\endgroup\$ – user202729 May 24 '18 at 11:52
  • 1
    \$\begingroup\$ I think that the choice of JavaScript was one of the mistakes of the original formic functions challenge. The way I see it, it is like using a jackhammer to crack a nut, sure you can do it but Javascript is a lot of machinery for the task and some things you want like functional purity are lacking. I'm not even specifically opposed to Javascript, I think that any other production programming language would be overkill for the task even if it had functional purity. I'm suggesting a small language that could be programmed in about 30 min and learned in about 2 min. \$\endgroup\$ – Wheat Wizard May 24 '18 at 15:18
  • 1
    \$\begingroup\$ @HatWizard I can't imagine a language that takes 2 minutes to learn to be nearly enough. I'm not against this idea in general, though. \$\endgroup\$ – Alion May 24 '18 at 16:23
  • 2
    \$\begingroup\$ @HatWizard a learning time of 2 minutes and a language powerful enough to have many approaches to the challenge (i.e. so not just specialized for pattern matching (even if that's the best option out there)) don't go together. Sure, >90% of my FF pattern matching code is just a ton of (nested) .maps and arrays but others might prefer different styles (e.g. Alions framework was class based, others just went linearly). For the original FF I thought of making a language specifically for my pattern matching ideology, but gave up as the requirements for me to consider it usable were too big. \$\endgroup\$ – dzaima May 24 '18 at 16:35

Make A Full Dobble™ Deck

Dobble (A.K.A. Spot It!) is a deck of (55) cards each of which has a set of (8) distinct symbols, such that every pair of cards matches on exactly one symbol and all symbols are members of pairs.

Dobble cards

The base aim of any of the games one plays with a Dobble deck is to find the matching symbols between pairs of cards quicker than your competitors; if you've never played I recommend it.

The deck as sold contains 55 cards and uses 57 symbols, but it is actually a "Full Dobble Deck" of 57 cards with 2 missing. If the missing 2 cards were added there would be 8 distinct symbols on each card such that each symbol would appear 8 times across the deck. Here is a deck I've been playing with, each row being a card (with the 2 missing cards added and asterisked):

  Anchor     Apple      Bird       Dinosaur   Dolphin    Ghost      Ladybird   Turtle
  Anchor     Bang       Car        Clef       Flower     Key        Lips       Lock
  Anchor     Bolt       Clown      Glasses    No-entry   Snowman    Spider     Target
  Anchor     Bomb       Bottle     Dog        Heart      Ice-cube   Moon       Zebra
  Anchor     Bulb       Cactus     Dragon     Flame      Scissors   Sun        Tree
  Anchor     Candle     Clover     Hand       Man        Skull      Snowflake  Splat
  Anchor     Carrot     Cheese     Clock      Hammer     Knight     Maple      Web
  Anchor     Cat        Drop       Eroteme    Eye        Igloo      Pencil     Yin-yang
  Apple      Bang       Igloo      Maple      Moon       Scissors   Snowflake  Spider
  Apple      Bolt       Cactus     Car        Carrot     Heart      Pencil     Skull
  Apple      Bomb       Cat        Hand       Lock       Snowman    Tree       Web
  Apple      Bottle     Clover     Dragon     Flower     Hammer     No-entry   Yin-yang
  Apple      Bulb       Cheese     Clown      Drop       Key        Man        Zebra
  Apple      Candle     Clef       Clock      Dog        Eroteme    Flame      Target
  Apple      Eye        Glasses    Ice-cube   Knight     Lips       Splat      Sun
  Bang       Bird       Flame      Glasses    Heart      Man        Web        Yin-yang
  Bang       Bolt       Bottle     Clock      Dinosaur   Drop       Hand       Sun
  Bang       Bomb       Carrot     Clown      Dragon     Eroteme    Ghost      Splat
* Bang       Bulb       Dog        Eye        Hammer     Ladybird   Skull      Snowman
  Bang       Cactus     Candle     Cat        Dolphin    Knight     No-entry   Zebra
  Bang       Cheese     Clover     Ice-cube   Pencil     Target     Tree       Turtle
  Bird       Bolt       Bomb       Candle     Cheese     Eye        Flower     Scissors
  Bird       Bottle     Eroteme    Key        Knight     Skull      Spider     Tree
  Bird       Bulb       Carrot     Clef       Hand       Ice-cube   Igloo      No-entry
  Bird       Cactus     Drop       Hammer     Lock       Moon       Splat      Target
  Bird       Car        Cat        Clover     Clown      Dog        Maple      Sun
  Bird       Clock      Dragon     Lips       Pencil     Snowflake  Snowman    Zebra
  Bolt       Bulb       Clover     Dolphin    Eroteme    Lips       Moon       Web
  Bolt       Cat        Flame      Ghost      Hammer     Ice-cube   Key        Snowflake
  Bolt       Clef       Ladybird   Maple      Splat      Tree       Yin-yang   Zebra
  Bolt       Dog        Dragon     Igloo      Knight     Lock       Man        Turtle
  Bomb       Bulb       Car        Dinosaur   Knight     Snowflake  Target     Yin-yang
  Bomb       Cactus     Clock      Clover     Glasses    Igloo      Key        Ladybird
  Bomb       Clef       Dolphin    Hammer     Man        Pencil     Spider     Sun
  Bomb       Drop       Flame      Lips       Maple      No-entry   Skull      Turtle
  Bottle     Bulb       Candle     Ghost      Glasses    Lock       Maple      Pencil
  Bottle     Cactus     Clef       Clown      Eye        Snowflake  Turtle     Web
  Bottle     Car        Cheese     Dolphin    Flame      Igloo      Snowman    Splat
  Bottle     Carrot     Cat        Ladybird   Lips       Man        Scissors   Target
  Bulb       Cat        Clock      Flower     Heart      Spider     Splat      Turtle
  Cactus     Cheese     Dog        Ghost      Hand       Lips       Spider     Yin-yang
* Cactus     Dinosaur   Eroteme    Flower     Ice-cube   Man        Maple      Snowman
  Candle     Car        Dragon     Drop       Ice-cube   Ladybird   Spider     Web
  Candle     Carrot     Key        Moon       Snowman    Sun        Turtle     Yin-yang
  Candle     Clown      Dinosaur   Hammer     Heart      Igloo      Lips       Tree
  Car        Clock      Eye        Ghost      Man        Moon       No-entry   Tree
  Car        Eroteme    Glasses    Hammer     Hand       Scissors   Turtle     Zebra
  Carrot     Clover     Dinosaur   Eye        Flame      Lock       Spider     Zebra
  Carrot     Dog        Dolphin    Drop       Flower     Glasses    Snowflake  Tree
  Cat        Cheese     Clef       Dinosaur   Dragon     Glasses    Moon       Skull
  Cheese     Eroteme    Heart      Ladybird   Lock       No-entry   Snowflake  Sun
  Clef       Clover     Drop       Ghost      Heart      Knight     Scissors   Snowman
  Clock      Clown      Dolphin    Ice-cube   Lock       Scissors   Skull      Yin-yang
  Clown      Flame      Flower     Hand       Knight     Ladybird   Moon       Pencil
  Dinosaur   Dog        Key        No-entry   Pencil     Scissors   Splat      Web
  Dolphin    Dragon     Eye        Hand       Heart      Key        Maple      Target
  Flower     Ghost      Igloo      Skull      Sun        Target     Web        Zebra

This is actually a Full Dobble Deck of order N=7, where the order defines the number of :

  • symbols (N2+N+1);
  • cards (also N2+N+1);
  • symbols per card (N+1); and
  • cards containing any given symbol (also N+1)

A Full Dobble Deck is analogous to a finite projective plane with points and lines as cards and symbols (or as symbols and cards) and thus may be constructed for any prime-power order (it is an open question whether finite projective planes exist for any non-prime-power order). We shall restrict ourselves to prime orders (it is much simpler to implement).

For example here is a Full Dobble Deck of order 3 (PG(2,3)) using 13 objects/colours (lines) and 13 cards (points) with 4 colours per card (lines incident with each point):

Dobble-3 = PG(3,2)

...and here it is as a list of cards containing the objects [0,12]:


The challenge

Given a prime (N) yield a Full Dobble Deck of that order in any convenient form.
One must be able to observe completion for N=11 (no brute forcing here)
For any other input undefined behaviour is acceptable.

* You may alternatively take as input N+1 or N2+N+1

Here is a Python program that validates a potential Full Dobble Deck (it must be given as a valid list of lists in Python syntax such as the "list of cards containing the objects [0,12]" example above).

| |
  • \$\begingroup\$ You might want to consider some performance constraint which eliminates brute force approaches and forces people to think about the mathematics. \$\endgroup\$ – Peter Taylor May 29 '18 at 11:15
  • \$\begingroup\$ @PeterTaylor Thanks for having a look at this. I was thinking of having a "one must be able to observe it complete successfully for N=11" but if you have a more concrete idea for a constraint do let me know (maybe it should simply be "N=11 in one minute"? I should probably code something up in a less efficient language to try...) On another note I am also wondering whether to restrict the input from prime-powers to just prime as supporting prime-powers as well as primes adds some complexity to the requirements on the implementation; still mulling, any further input very much appreciated. \$\endgroup\$ – Jonathan Allan May 29 '18 at 12:48
  • 1
    \$\begingroup\$ Observing it complete is preferable to "in one minute" because it means that if I have a slower computer it doesn't invalidate my answer, but merely slows down when I can post it. Using just primes is certainly much easier because there's no need to build field towers with irreducible polynomials. I personally would be much more inclined to answer if it's primes only. \$\endgroup\$ – Peter Taylor May 29 '18 at 14:03
  • \$\begingroup\$ Related/dupe maybe? \$\endgroup\$ – Dom Hastings May 29 '18 at 20:12
  • \$\begingroup\$ @DomHastings weird I though, I'd searched both Dobble and Spot It, now I see two. The only things this would bring over the other code-golf question would be: (1) the alphabet there is bounded; and (2) implementing a constraint like Peter suggested. The current answer would need to iterate across (a least a large proportion of) the c(133,12) = 3.8*10^16 possible cards for N=11. I dont think (1) stops this being a dupe, but (2) might. Thoughts anyone? \$\endgroup\$ – Jonathan Allan May 29 '18 at 21:22
  • \$\begingroup\$ @DomHastings Oh, and the brute-force solution there actually fails for N=4 (the first non-prime prime-power) even though I was planning on not requiring that to work the other (at present) does. \$\endgroup\$ – Jonathan Allan May 29 '18 at 22:33
  • \$\begingroup\$ I only vaguely remembered it from when I first played Dobble too! Agree that the answer from the challenge I linked can't be copied over which I think is the main criteria for dupe, right? But the reverse might be true, all answers for your challenge should also solve the previous? So not sure if that make the older one a dupe, but that sounds too political for me! \$\endgroup\$ – Dom Hastings May 30 '18 at 11:39
  • 1
    \$\begingroup\$ If the input for this one is restricted to N being prime (or even prime-power) then answers to this would not necessarily solve the other. Furthermore while the other is limited to an alphabet of 62 (while I plan on an execution observation for N=11 which has an alphabet of size 133) answers to the other would not necessarily answer this one. Seems like maybe it's not a dupe after all, even though the premise is exactly the same! \$\endgroup\$ – Jonathan Allan May 30 '18 at 12:03

Tower Defense (Abandoned)

Anyone is free to take over this challenge and fork as necessary. Just give me credit ;)

Tower Defense Example

View it here | Chat

Tower Defense is a format for casual games that was popularized in the Flash era. The player places towers that shoot down invaders moving along a predefined path.


Two submissions will compete against each other to invade the other player's village without being invaded themselves. They will have the ability to place towers, upgrade them, and spawn invaders to attack the enemy village. The game will be simulated deterministically in a turn based fashion, with each player being able to do one action each turn.

The game board is made up of two paths, each 100 spaces long. Each player begins with 500 gold, which is used for building towers and spawning invaders; and 100 life. Your objective is to bring your opponent's life down to 0. If neither player has been defeated after 100000 turns, the winner will be the player with the most life at that point, with ties being broken by who has the most gold at that point. If, somehow, there is still a tie, the match will be considered a tie.


Every 10 turns, players will receive gold. Initially, they receive 10 gold, but this amount increases by 3 every 100 turns.

Each time you successfully get an invader through your opponent's defenses, your income increases by 1 and you receive a portion of your income proportional to how much HP the invader had left.

Each time one of your towers defeats an invader, you receive gold. (More on that below)


Each space on the path can house one tower. There are 3 types of towers, which have a range and a power. It takes 10 turns for a tower to be ready after it is built. Towers can be upgraded either with a wider range or an increased power, in increments of 1. There is no hard limit to how many times a tower can be upgraded.

Range refers to how many spaces away from the tower that can be reached by the tower's abilities. A range of 0 means that only the space that the tower is on is affected by the tower's attacks.

Power has a different meaning depending on the kind of tower.


Each turn, turrets fire at the invader within range that is farthest along the path to your village. They deal damage equal to the tower's power.

Turrets begin with a range of 1 and a power of 1.


Stunners fire at the invader within range that is farthest along the path to your village. However, instead of dealing damage, they stun the invader for a number of turns equal to the tower's power. After firing, stunners cannot fire again for their power + 1 turns. Stunners will not fire at invaders that are already stunned.

Stunners begin with a range of 0 and a power of 3


When an invader is on the same space as the bomb tower, it triggers and deals damage equal to its power to all invaders within its range. After being triggered, it cannot fire again for another 5 turns.

Bombs begin with a range of 2 and a power of 2


Each turn, you may spawn an invader. At minimum, it costs 10 gold and has a base HP of 10. You can spend additional gold to increase its power:

  • (1G) +1 HP
  • (10G) +1 Defense (reduce damage taken by 1, but not lower than 1)
  • (10G) +1 Stun resistance (reduces stun time by 1 turn)

You are limited on the maximum stats. You start off unable to boost stats, but every 100 turns, the maximum increases by 5

There can only be one invader on each space of the board and invaders cannot pass through each other. You cannot spawn an invader if there is already an invader on the first space of the board. Therefore, a potential counterplay from defenders to prevent massive hordes of invaders is to put stunners on the first few spaces.


The main game / AI driver is here (still a work in progress)

Submission logistics TBD

Both players will have complete knowledge about the state of the game and will be allowed to maintain state from the beginning of the game. They may not directly modify the game state. Any attempts to do so will be disqualified as will any attempt to obfuscate such an attempt.

(api description will go here)

Defenders should return an object with an action property that is either 'build', 'upgrade', or 'destroy'. Each requires some additional properties to be set: (will add later)

Invaders should return an object which contains any stat boosts desired: hp, defense, and stunRes.

Both defenders or invaders may also return undefined or null to indicate not taking an action.

AIs must return their desired action in less than 10 milliseconds, averaged over 100 turns. Invalid actions returned by the AI will be ignored.


All submissions will compete against all other submissions in a round-robin tournament. The bot that wins the most matches is declared the winner. In the event of a tie, the number of turns it took to win will be totaled for all winning matches with the smallest cumulative turn count to victory wins. In the unlikely event of a further tie, the turns to loss will be totaled for all losing matches and the bot with the highest cumulative turn count to loss wins.

Only one submission per user can be scored in the round-robin tournament.


  • No abusing standard loopholes
  • No direct modification of the game state passed to you. It will not be defensively deep-copied. Don't obfuscate your code to try to hide state modification.
  • Any uncaught exceptions will result in disqualification.
  • Implementations must be totally deterministic, i.e. random number generators are only allowed if seeded consistently (either with a constant or with game state) and must use isolated random state which the other AI in play cannot access.
  • Submissions shall include an explanation of the AI's strategy.
| |
  • 2
    \$\begingroup\$ The biggest issue you are going to have here is balance. Making sure that the towers are evenly balanced and that both sides have a decent chance at winning each wave (in order to discriminate who is better). It may be worth building an actual simulation and actually playing the game before making it a challenge. \$\endgroup\$ – Nathan Merrill Apr 19 '18 at 18:59
  • 1
    \$\begingroup\$ I'd argue that this is just a king-of-the-hill. Cops-and-robbers have a drastically different posting format that you don't want, and we've already had challenges where there are different types of submissions \$\endgroup\$ – Nathan Merrill Apr 19 '18 at 19:01
  • \$\begingroup\$ Why don't you allow towers to be adjacent? It's easy to check if they have blocked all paths to the exist. Modifying the number of turns between rounds is useless as far as I can tell. It's far more effective to have massive waves than trying to join waves together. \$\endgroup\$ – Nathan Merrill Apr 19 '18 at 19:07
  • \$\begingroup\$ You should tag this with the language that submissions should be in. \$\endgroup\$ – Nissa Apr 23 '18 at 14:10
  • \$\begingroup\$ What constitutes an "obfuscated submission"? This needs to be defined more clearly. Side note: some people tend to write (subjectively) obfuscated code in the first place. \$\endgroup\$ – Alion Apr 24 '18 at 10:05
  • 1
    \$\begingroup\$ You should specify the base of the logarithms used in your calculations. \$\endgroup\$ – Alion Apr 24 '18 at 10:19
  • \$\begingroup\$ "Each Defender will face off against each Invader (not including any submissions by him)" should probably be reworded into "Each Defender will face off against each Invader, excluding pairs with identical authors". I had a hard time understanding the sentence. Also, this rule will heavily influence the results. Someone might post multiple fantastic Defenders and a decent Invader, and their Invader will have an easier time than the rest because it doesn't have to compete against the state-of-the-art. I know what you were trying to achieve, but a simple "don't cooperate" would probably suffice. \$\endgroup\$ – Alion Apr 24 '18 at 10:35
  • \$\begingroup\$ How does the damage scale with the power, exactly? "Power affects damage for bombs and turrets" probably isn't clear enough. Also, what is the base power of the stunner? I'd recommend rethinking and rewording that section in general - it feels clunky to read. \$\endgroup\$ – Alion Apr 24 '18 at 11:05
  • \$\begingroup\$ Nitpick: a one-dimensional "grid" can be called a tape, for example. \$\endgroup\$ – Alion Apr 24 '18 at 11:10
  • \$\begingroup\$ Oh, I completely misunderstood the way invader stats work. I thought they were permanent buffs. I have removed the relevant comments. \$\endgroup\$ – Alion Apr 24 '18 at 11:24
  • \$\begingroup\$ Is the stat boost limit cumulative or per stat? If I have a stat boost limit of 5, am I allowed to spawn an invader with +5 HP, +5 Defense and +5 Stun Resistance? \$\endgroup\$ – Alion Apr 24 '18 at 14:16
  • \$\begingroup\$ For a similar challenge structure, see: codegolf.stackexchange.com/q/51029/31203 \$\endgroup\$ – MegaTom Apr 25 '18 at 2:48
  • \$\begingroup\$ 1. The symmetry could be restored by making each entry both an invader and an attacker, with the win going to the first to wipe the other out. That introduces the need to balance your gold between attack and defence. 2. I'm not seeing any money awarded for destroying an invader. That's somewhat unusual for tower defence games. 3. There are some ambiguities. Does "already-stunned invader" mean previously stunned or currently stunned? Does "an invader is immediately in front of them" mean on the same square or on a square numbered one less? \$\endgroup\$ – Peter Taylor Apr 25 '18 at 10:33
  • \$\begingroup\$ @Alion an obfuscated submission would be one that deliberately tries to hide implementation details- especially if it tries to sneak in direct game state modification. For example, if you implemented a bot in JSFuck, that would obviously be obfuscated \$\endgroup\$ – Beefster Apr 26 '18 at 18:02
  • 1
    \$\begingroup\$ I have been creating a KoTH tower defence challenge in the background for a while and was a little saddened that you have beaten me to the punch... however after reading your spec, I think the tower defence challenge I am working on will have sufficently different mechanics to allow for both challenges to exist without being duplicates. I just need to get it to the point where it can be presented here in the sand box. That being said, I look forward to participating in your challenge. \$\endgroup\$ – Moogie Jul 20 '18 at 4:30

Give numbers space

Given a list of integers, adjust each number by at most ±1 so that in the resulting list, each number is at least 2 apart from each of its neighbors. That each, each entry n can be replaced with n-1, n, or n+1, and any two adjacent entries x and y must have abs(x-y) ≥ 2. The output is a list of the same length as the input.

You will not get an input where this is impossible, such as [5, 4, 4, 5]. The input will have at least two elements.

Examples (other outputs are possible):

[-5, -6] -> [-5, -7]
[1, 1, 1] -> [2, 0, 2]
[2, 2, 3, 3] -> [3, 1, 4, 2]
[0, 5, -1] -> [0, 5, -1]
[4, 4, 4, 4, 4, 4, 4, 3, 3, 3] -> [5, 3, 5, 3, 5, 3, 5, 2, 4, 2]
[4, 4, 4, 4, 4, 4, 4, 5, 5, 5] -> [3, 5, 3, 5, 3, 5, 3, 6, 4, 6]
[1, 1, 2, 4, 6, 7, 7] -> [2, 0, 2, 4, 6, 8, 6]
| |
  • 5
    \$\begingroup\$ [5,4,4,5] is impossible I think. The two 4s have to become a 3 and a 5 to not be close to each other, and then whichever one becomes a 5, you can't adjust the other 5 away from it. \$\endgroup\$ – user62131 Nov 24 '16 at 5:21
  • 4
    \$\begingroup\$ Maybe this could be a decision problem then? \$\endgroup\$ – Zgarb Nov 24 '16 at 8:28

Game of Lives

In this , your goal is to create a GOL (Game of Life) pattern that creates the most live cells after \$n\$ steps. The twist is, you will be competing against 3 other patterns on the same playing field at the same time.

Here are the rules of the Game of Life, with a couple of additions:

  • Each player's starting living cells will be a specific colour.
  • Any live cell with 2 or 3 live neighbours will stay alive, otherwise they'll die
    • Note that 'neighbours' includes diagonals, so there are 8 possible neighbours for a cell.
  • Any dead cell with exactly three neighbours will become a live cell with the colour of the most common neighbouring cell. If there is no majority, it will become a neutral colour, which won't count for further conversions.
    • 2 Reds + 1 Blue = Red
    • Red + Blue + Green = Neutral
    • 2 Neutrals + Red = Red
  • The playing field will be \$x\$ by \$x\$, where each quarter of the field is each player's starting configuration.
  • Cells outside the playing field will always be considered as dead, and cannot be resurrected.
  • Each starting configuration will be flipped and rotated so the right and bottom sides face the enemy.

For example, if your submission was:

Start corner

And you plotted them against one another, the starting configuration could be:

enter image description here

Note how the bottom right isn't symmetrical, but still has the correct sides facing inwards.

Your submission should be a \$x/2\$ by \$x/2\$ GOL pattern that assumes it is in the top left corner.

Rounds will be run until only one competitor remains or the whole pattern repeats, where the competitor with the most cells when the pattern repeats is the winner.


  • I haven't decided yet what sizes the playing field should be (\$x\$), nor how long each game should run (\$n\$).
    • I was thinking about a 128 by 128 playing field, with 64 by 64 for each player. Is that too large or too small? For reference, the submission would be the size of: enter image description here with some gliders and stuff for reference. Is that too many or too little? I haven't really got much reference.
  • I am working on a visual controller like the Formic Functions question
  • Overall winner? Check all combinations (way too much time as more submissions are added)? Tournament structure (multiple rounds per elimination)?
| |
  • 1
    \$\begingroup\$ So... where's the programming part? \$\endgroup\$ – Alion Nov 1 '18 at 12:36
  • 2
    \$\begingroup\$ @Alion Your submission is a GOL pattern. I guess you could say you're programming in GOL \$\endgroup\$ – Jo King Nov 1 '18 at 12:52
  • \$\begingroup\$ Fairy enough. I just think it's a missed opportunity. You could easily make it into a JavaScript competition, where programs just run multiple rounds of the currently planned game, having access to what happened last round, and thus being able to iterate on their patterns. You don't exclude anything - at the start, you're just going to get a lot of static entries (and I don't think anyone's going to be discouraged by the fact the they have to write return before their pattern). \$\endgroup\$ – Alion Nov 1 '18 at 13:03
  • \$\begingroup\$ Unless you want to see the best static pattern, full stop. I can see that being fun as well - my comment was just a suggestion. \$\endgroup\$ – Alion Nov 1 '18 at 13:04
  • \$\begingroup\$ 1) Is it just me, or is the example picture screwed up? The distances to the dotted lines don't match up. 2) My computer would greatly appreciate it if the side length of the board was a power of 2 - the closest size to that is 128x128. 3) You could make the game last until the pattern settles down, i.e. starts being periodic. \$\endgroup\$ – Alion Nov 1 '18 at 14:36
  • \$\begingroup\$ I don't know if the challenge is interesting or not, mainly because it's very unintuitive to "program" in GoL. \$\endgroup\$ – user202729 Nov 1 '18 at 15:15
  • \$\begingroup\$ @Alion "best" static pattern? I think how a pattern behaves also depends on its opponents. \$\endgroup\$ – user202729 Nov 1 '18 at 15:16
  • \$\begingroup\$ @Alion I've fixed the image and changed the field size to 128, thanks. \$\endgroup\$ – Jo King Nov 1 '18 at 23:48
  • \$\begingroup\$ @user202729 It might not be intuitive, but it is possible. Very possible. \$\endgroup\$ – Jo King Nov 1 '18 at 23:52
  • \$\begingroup\$ We need to clarify the behavior on the borders outside of the whole playing field. Does the grid extend indefinitely? Or does it wrap around? Or maybe simply hard dead cells (cannot turn to alive whatsoever) outside the given area? \$\endgroup\$ – Bubbler Nov 2 '18 at 5:32
  • 1
    \$\begingroup\$ @Bubbler Cells outside the playing field will always be considered as dead, and cannot be resurrected. Though wrapping cells might be interesting... \$\endgroup\$ – Jo King Nov 2 '18 at 5:44
  • \$\begingroup\$ Oops, I didn't notice that. \$\endgroup\$ – Bubbler Nov 2 '18 at 6:04
  • 2
    \$\begingroup\$ If they are all different colours, then the cell will be randomly picked from those colours. Given the nature of complex GoL patterns, I would suspect that one random cell choice can make a huge difference, so it might be nicer to keep the outcome deterministic and just kill such a cell. \$\endgroup\$ – Laikoni Nov 2 '18 at 8:49
  • 5
    \$\begingroup\$ @Laikoni For clarity: we're talking about cell colors being chosen randomly, right? While I agree that this could generate large bias within a single game, I don't think it matters in the grand scheme of things. As for the solution (if this is to be considered a problem) - breaking the GoL rules seems odd. For example, a 3-color blinker would just disappear. How about adding an additional, neutral color in that case? It would behave the same way that all the other colors behave, but wouldn't give any points to anyone. A 3-color blinker would lose its outer colors that way, but keep existing. \$\endgroup\$ – Alion Nov 2 '18 at 10:29
  • 1
    \$\begingroup\$ You should probably explicitly mention that GoL uses a Moore neighborhood (which includes diagonals), as opposed to a von Neumann neighborhood (which does not). \$\endgroup\$ – user45941 Nov 2 '18 at 23:12

Do-nothing Polyglot

This challenge requires you to write a polyglot which contains a comment in as many languages as possible.

The comment must say This is a polyglot comment.

The program must do nothing at all.

Besides comments, your code may contain no-ops from the language(s) you are using, if it helps incorporate more languages into your answers. For example in bash we could use :. Or in the family, something like the following may be used, as long as it compiles:

if (0) {
    statements with side effects

Since this is a challenge, the answer with the most languages wins, so I think this should also be tagged

| |
  • \$\begingroup\$ I think it is funny that the content of the comment makes it so that H9+ cannot be included. Yes, tag it [code-challenge]. \$\endgroup\$ – Justin Mar 16 '14 at 2:27
  • \$\begingroup\$ Many languages use # or // to signify comments. Perhaps restricting the counting so that each type of comment is counted only once. In other words, //This is a polyglot comment would only count for 1 language, not fo C, C++, Java, ... \$\endgroup\$ – Justin Mar 16 '14 at 5:13
  • 4
    \$\begingroup\$ What is a "program" for the purposes of this question? In particular, are compiled languages going to be excluded because the compiler won't be able to find an entry point? \$\endgroup\$ – Peter Taylor Mar 16 '14 at 17:33
  • \$\begingroup\$ What does no-ops mean? \$\endgroup\$ – Mohammad Mar 18 '14 at 17:37
  • 2
    \$\begingroup\$ I think that in some esolangs it's not entirely decided what counts as a comment. Maybe you should say that the code must contain the text this is a polyglot comment. \$\endgroup\$ – Esolanging Fruit Mar 16 '17 at 4:24
  • \$\begingroup\$ Thanks! Posting this (after I edit it) \$\endgroup\$ – Christopher May 2 '17 at 20:40
  • \$\begingroup\$ Yeah I removed the post as it was horrible and not well recived \$\endgroup\$ – Christopher May 16 '17 at 15:17

You say goodbye, and I say hello

In this challenge, you have to make a program that outputs Hello, World!. That's not all though! When the program is reversed, it has to output Goodbye, World!.

Unfortunately, there are a few boring rules:

  • No using comments, i.e., the Python code print"Hello, World!"#"!dlroW ,eybdooG"tnirp is illegal

This is , so try to do it in the least number of bytes.

(Should the forwards/backwards tasks be changed? I think they are probably too easy. Let me know if you have any suggestions.)

| |
  • 2
    \$\begingroup\$ You're missing a golden opportunity to make a Beatles reference. \$\endgroup\$ – a spaghetto Nov 4 '15 at 18:11
  • 2
    \$\begingroup\$ This is a good point. Typically in good palindrome challenges at least comments should be banned; you can take a look at this for some examples of good rules in a palindrome challenge. \$\endgroup\$ – a spaghetto Nov 5 '15 at 21:06
  • 1
    \$\begingroup\$ @quartata Thank you for the example! This is what the sandbox is good for. \$\endgroup\$ – DanTheMan Nov 6 '15 at 17:35
  • 1
    \$\begingroup\$ Your answer may...? :) \$\endgroup\$ – trichoplax Nov 8 '15 at 1:07
  • \$\begingroup\$ Do you think I can just go ahead and post this as a challenge? \$\endgroup\$ – DanTheMan Nov 9 '15 at 18:05
  • 2
    \$\begingroup\$ What counts as a comment? Unexecuted code? Strings which are pushed and never used? etc etc \$\endgroup\$ – Sp3000 Nov 10 '15 at 10:06
  • \$\begingroup\$ I don't think it's too easy. Easy questions get lots of answers and therefore plenty of upvotes for you. That said, there's probably a duplicate or near duplicate out there somewhere. \$\endgroup\$ – Level River St Nov 16 '15 at 10:43
  • \$\begingroup\$ it makes lots of language impossible. Maybe comment have penalty \$\endgroup\$ – l4m2 Dec 31 '17 at 14:43

What shape is that polygon?

Given an ASCII figure made of /, \, |, and _, write a program that determines (1) if the figure is a closed, non-self-intersecting polygon (meaning it has at least three sides that connect to form a loop), and if so, (2) how many sides the polygon has and (3) if the polygon is convex (all internal angles are less than 180˚) or concave (not convex, note that no polygons have 180˚ angles).

The multiline input is the ASCII figure. It can be assumed that the input only contains the four characters listed above.

If the figure is not closed or self-intersects (or has more than 2 sides connecting at the same point), the program should print Not a polygon.

The number of sides the polygon has is determined by the following chart.

Sides   Name
3       Triangle
4       Quadrilateral
5       Pentagon
6       Hexagon
7       Heptagon
8       Octagon
9       Nonagon
10      Decagon
11      Undecagon
12      Dodecagon
>12     n-gon (where n is the number of sides)

The output should be in the format <concavity> <polygon name> if (1) is satisfied.

Test cases

 /  \__

==> Concave hexagon


==> Concave 17-gon


==> Not a polygon

/ \
| |

==> Convex octagon

I need a little assistance on getting stricter definitions of points intersecting, so help would be appreciated. Thanks!

| |
  • 1
    \$\begingroup\$ I like the concept of this challenge. A good test case would be including a line that goes inside the polygon as well as lines that doesn't even touch the polygon (unless you are going to guarantee that they will touch) \$\endgroup\$ – Nathan Merrill Dec 6 '15 at 19:45
  • \$\begingroup\$ Your first two examples look wrong: those polygons are clearly concave. \$\endgroup\$ – Peter Taylor Dec 7 '15 at 9:45

Capsa, a card game KotH!

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

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

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

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

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

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

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

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

Rules of play:

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

Possible scoring systems:

  • Bots are judged by the number of games they win over (TBD) games that they play. So if we have seven bots to test, we'll play them until every bot has played more than (TBD) games.
  • Bots are judged by the number of cards they have left at the end of the game. (The winner will obviously have 0 cards at the end of the game).

Here is the link to a preliminary controller and two bots to test against.

| |
  • 1
    \$\begingroup\$ "The cards are dealt between everyone, so that everyone has 13 cards" belongs in the "rules of play" section, even if that means having to repeat it. \$\endgroup\$ – Peter Taylor Dec 30 '15 at 11:09
  • \$\begingroup\$ @PeterTaylor Done. If you have any comments on the controller linked at the bottom of this post, I'd love to hear them. Thanks \$\endgroup\$ – Sherlock9 Dec 30 '15 at 11:27

Let's Play Unikong

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


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


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


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

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

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

Reverse the lengths


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

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

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


Consider the input array

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

The concatenation of A is

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

and its length sequence is

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

The correct output is


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

Rules and scoring

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

Test cases

TODO: make more

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

Sandbox comments

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

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

The Secret Handshake

This is based off of this sandbox comment.

This is a challenge of secrecy.

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

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

The Gameflow:

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

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

Sandbox Notes

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

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

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

Solve the Nonogram!

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

What is a Nonogram?

Nonogram Puzzle

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

So the solution to the above Nonogram would be:

Solved nonogram

Implementation Details

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

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

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


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

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

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

There can be only 1!

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

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

The operators at your disposal are:

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

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

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


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


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

Set of Numbers:

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

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

Scoring System:

Your score is determined like so:

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


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

Telegraphy Golf: Decode Baudot Code


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

Baudot 5-key keyboard

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

5 bits??

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


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

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

Baudot's Code

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

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

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

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

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

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

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

The decoder always starts in Letter mode.

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

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

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

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



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

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

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

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

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

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

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

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

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

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


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

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


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


  • Standard loopholes are forbidden.

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

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

Test Cases

Input: 001101000010100111101110010101
Output: BAUDOT
Input: 11010010001001100011110111101111100
Output: HELLO
Input: 01011100000010000001000101000011100000011010111010
Output: MAY 15TH
Input: 00010001000001000001011101110011100101010010110101010001111100101
Output: 32 FOOTSTEPS
Input: 10110000110101011100111100001111011010000001101110
Output: GOLF
Input: 000100011000001111100000100010110111001100010110010000111111
Output: 8D =( :P
Input: 0000100001000010000100010001111011111011000011100010001
Output (4 leading spaces):     -/=/-
| |
  • \$\begingroup\$ This is quite similar to the Morse decoding question. The main thing it adds is the three control characters. It might be worth adding a cross-reference in a comment after posting the question. \$\endgroup\$ – Peter Taylor Sep 19 '16 at 21:56
  • 1
    \$\begingroup\$ Can the transmission start with erasure? \$\endgroup\$ – Sp3000 Sep 20 '16 at 1:00
  • \$\begingroup\$ @Sp3000 No. Good catch. I had a note to that effect but apparently accidentally deleted it. \$\endgroup\$ – Jordan Sep 20 '16 at 1:07
  • \$\begingroup\$ Can an erasure follow a shift that is acting as a space? \$\endgroup\$ – Phlarx Sep 20 '16 at 14:16
  • \$\begingroup\$ @Phlarx Nope. ER will never follow LS or FS. \$\endgroup\$ – Jordan Sep 20 '16 at 14:17
  • \$\begingroup\$ Thank you for your feedback, all. I've posted the challenge: codegolf.stackexchange.com/questions/94056/… \$\endgroup\$ – Jordan Sep 21 '16 at 13:23
  • \$\begingroup\$ Don't forget to take of this answer in the Sandbox. " When you think your challenge is ready for the public, go ahead and post it, replace the post here with a link to the challenge and delete it. " \$\endgroup\$ – Linus Sep 22 '16 at 19:29

my first post on here, be gentle ;)

Find all anagrams within a text

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

The assignment

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

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


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


  • All other characters are part of the word and treated as is, so "a" and "á" are not the same.


Given the following input text (the actual text I was given as example by school :P, no idea where this text is coming from...)

Parts of the world have sunlight for close to 24 hours during summer. Dan went to the north pole to lead an expedition during summer. He had a strap on his head to identify himself as the leader. Dan had to deal with the sun never going down for 42 consecutive days and his leadership strap soon became a blindfold. He wondered what kind of traps lay ahead of him.

the following output would be correct:

  • 24, 42
  • deal, lead
  • and, dan
  • parts, strap, traps

Or this would also be correct:

24, 42 | deal, lead | and, dan | parts, strap, traps

This one would not

24, 42 , deal, lead , and, dan , parts, strap, traps

(since the groups are not obvious)

My own (non golfed) version to check

The is the exact program I submitted to school back then. You may use it to check your own results.

Added bonus: If it happens to be that this program has a bug (I haven't found them yet) your submission is allowed to have it as well, since it is used to check the result. (In that case you are of course not required to have said bugs)

#include <string>
#include <iostream>
#include <fstream>
#include <map>
#include <set>
#include <algorithm>
#include <cstring>

void stringRemoveInterpunction(std::string& string);
void stringToLower(std::string& string);
std::string stringToAnagramIdentifier(std::string word);

 * due to use of std::ispunct and std::tolower it may not work for text with non-ascii characters??!
int main(int argc, char* argv[]) {
    if (argc < 2) {
        std::cerr << "usage: " << argv[0] << " <filename>" << std::endl;
        return 1;

    std::ifstream fileStream(argv[1]);
    if (!fileStream) {
        std::cerr << "Could not open file " << argv[1] << std::endl;
        return 2;

    // map to store the anagrams, key is so called "anagram identifier", value is a list of the words.
    std::map<std::string, std::set<std::string>> anagrams;

    // read words separated by whitespace from the file
    for (std::string word; fileStream >> word;) {
        // remove interpunction & convert to lowercase, since casing should be ignored
        stringRemoveInterpunction(word); stringToLower(word);

        // add to anagrams-store

    // display all the anagrams
    for (auto anagram : anagrams) {
        // skip entries which contains only one item, no anagrams found
        if (anagram.second.size() <= 1) {

        // output a comma-separated list of the anagrams
        auto anagramIterator = anagram.second.begin();
        std::cout << *anagramIterator++;
        while (anagramIterator != anagram.second.end()) {
            std::cout << ", " << *anagramIterator++;
        std::cout << std::endl;

    return 0;

void stringRemoveInterpunction(std::string& string) {
    string.erase(std::remove_if(string.begin(), string.end(), std::ptr_fun<int, int>(&ispunct)), string.end());

void stringToLower(std::string& string) {
    std::transform(string.begin(), string.end(), string.begin(), std::ptr_fun<int, int>(&std::tolower));

std::string stringToAnagramIdentifier(std::string word) {
    // sort the characters
    std::sort(word.begin(), word.end());
    return word;

Sandbox Questions

  • Do i need to add other tags, or is just code-golf enough?
  • I'm not completely sure about the upper-limit of the input text. My idea was that the code should be able to handle any size input as long as its within the memory-limits of the language. Like you don't have to write "memory optimal code" or something, but also shouldn't asume it is smaller than X. I could also just pick an upper limit of "1 kilobyte" or something to avoid any uncertainty about the requirements I think this is fine now as it is.
  • Someone in the comments below asked how to handle special characters like $?() so I took a look at how my "check program" handled that and it strips them away before doing the anagram check. So I added a rule for that, but while writing that I felt it makes it needlessly complicated and I'm considering ditching that rule and altering my check-program to reflect that (but then I cant claim its the exact same anymore :( )
  • Any other parts that are not clear?
| |
  • \$\begingroup\$ What happens if there are 3 that are anagrams, such as eat ate tea? Are they all printed in one line / group? \$\endgroup\$ – FlipTack Dec 19 '16 at 17:27
  • \$\begingroup\$ @Flp.Tkc yes, like "parts, strap, traps" in the example \$\endgroup\$ – Olle Kelderman Dec 19 '16 at 17:29
  • \$\begingroup\$ I suggest you remove the grouping rule, since it's not really the interesting part of the challenge. It just adds code and limits the solutions. It's apparent which of the words that are together anyway. I do suggest they have to be grouped though, but without the need for delimiters. \$\endgroup\$ – Stewie Griffin Dec 20 '16 at 23:24
  • \$\begingroup\$ I think the memory rule is fine. I'm quite sure people will write a script that in theory would work for any input length if it wasn't for language or memory limitations. I also suggest you guarantee at least one character in the input. Otherwise people would need to add code just to handle empty input and that's not the interesting part of the challenge. \$\endgroup\$ – Stewie Griffin Dec 20 '16 at 23:29
  • \$\begingroup\$ You should add rules regarding special characters. Are it's, sit and its anagrams? What about hyphens? Can there be any special characters such as $?() etc? How are they treated? \$\endgroup\$ – Stewie Griffin Dec 20 '16 at 23:31
  • \$\begingroup\$ @StewieGriffin The grouping thing is a natural result of my solution to the problem back then, and imo its a fun part of the challenge, so I'm not totally sure about removing it. About the memory limit: I'm totally fine with the guarantee of at least one character if you think empty input needs special handling (i didnt think it would, but I dont really care :P) And yes, you are correct about special characters. I'd say "it's" is two words: "it" and "s". All special characters are ignored, so essentially regarded as whitespace between words. I'll add that \$\endgroup\$ – Olle Kelderman Dec 20 '16 at 23:35
  • \$\begingroup\$ welp, turns out I handled special characters differently, I strip them away from the word, so "it's" becomes "its", guess that'll be the rule then since I want to keep as close as possible to the original program \$\endgroup\$ – Olle Kelderman Dec 20 '16 at 23:48
  • \$\begingroup\$ @StewieGriffin I added a rule about special character handling, but I'm not completely sure about it, thoughts? (see my added "sandbox question") \$\endgroup\$ – Olle Kelderman Dec 21 '16 at 0:05
  • \$\begingroup\$ parsing and anagrams are relevant tags, maybe strings too, but I'm not sure about that one. \$\endgroup\$ – Stewie Griffin Dec 21 '16 at 7:43
  • \$\begingroup\$ !"#$%&'()*+,-./:;<=>?@[]^_{|}~ are all the non-alphanumeric ASCII-characters, except \` . I suggest you include the missing two symbols in the list to ignore, and say: "All non-alphanumeric characters (except spaces and newlines) must be trimmed away. So, it's and its are the same word." (You might want to rephrase that since my English isn't perfect, but something along those lines. If this is the rule then R2D2 and dr.22 will be anagrams, I'm not sure if that the desired behavior..? \$\endgroup\$ – Stewie Griffin Dec 21 '16 at 10:17
  • \$\begingroup\$ PS! I don't mean to be difficult, it's just that in my experience you'll get these questions sooner or later. So it's a good thing to sort it out while it's still in the Sandbox :) \$\endgroup\$ – Stewie Griffin Dec 21 '16 at 10:20
  • \$\begingroup\$ @StewieGriffin those two characters should have been included, look at the list from en.cppreference.com/w/cpp/string/byte/ispunct where I got it from, somehow I messed up the copy-paste :( And about "what is desired behaviour?" Im honestly not sure, I never really thought about it before you mentioned it and then I looked at how my sample program handled it. I remember putting in the ispunct-trim for stuff like commas after a word, im not sure about characters within the word... \$\endgroup\$ – Olle Kelderman Dec 21 '16 at 10:26
  • \$\begingroup\$ You can say that the input will not have any special characters except ' and -. Those two must be trimmed away. I think you must include those two, since these can be found in many texts. \$\endgroup\$ – Stewie Griffin Dec 21 '16 at 10:34
3 4 5

You must log in to answer this question.

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