What is the Sandbox?

This "Sandbox" is a place where Programming Puzzles & 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 and click "Answer This Question". Give the details of your challenge just as you would when actually posting it. Other users will help you improve your challenge by rating and discussing it. When you think your challenge is ready for the public, go ahead and post it, and mark it as posted here.

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

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

Submission Directory

This is a community-maintained list of the most active Sandbox submissions, sorted by major contest type. Add an entry to the top of this list if you add a new submission or update an old one. If you don't have enough reputation to edit questions you can ask in chat for a higher-rep user to add your submission for you. You may include a [status] indicator and tags to categorize your submission.

If this list grows too long you may remove entries that have been inactive for several days. It's best to remove submissions from this list once they've been posted to the main page.





524 Answers 524

It's Life, Jim, but not as we know it

You probably know Conway's Game of Life, the famous cellular automaton invented by mathematician John Conway. Life is a set of rules that, together, allow you to simulate a two-dimensional board of cells. The rules decide which cells on the board live and which ones die. With some imagination, you could say that Life is a zero-player game: a game with the objective to find patterns with interesting behavior, like the famous glider.


A zero-player game... Until today. You are to write a program that plays the Game of Life - and plays it to win, King of the Hill-style. Your opponent (singular) of course tries to do the same. The winner is either the last bot with any live cells, or the player with the most live cells after 5 minutes of clock time.

Game rules

The rules are almost the same as normal (B3/S23) Life:

  • A live cell with fewer than two friendly neighbors dies from starvation.
  • A live cell with two or three friendly neighbors survives.
  • A live cell with more than three friendly neighbors dies from overpopulation.
  • A dead cell with exactly three neighbors of the same player comes alive to fight for that player provided there are no enemy neighbors.

...but after each generation, both you and your opponent get the opportunity to intervene. You can awake up to a maximum of 30 cells to fight for you. (Who goes first is decided by the server.)

The board is a 1024×1024 cell square. All squares are initially dead. The borders do not wrap around (this is not a torus-shaped world) and are permanently dead.

This is is a contest in the spirit of Battlebots and Core Wars. However, unlike those two, you are supposed to run your implementation on your own machine. You fight the other contestants on a central arena server.


The arena server speaks a simple, compact TLV protocol over TCP. Messages have the following format:

^ Type (1 byte, ASCII)
 ^ Length (1 byte, unsigned int)
  ^ Values (Exactly length bytes long)

The meaning of the value depends on the type of message. For example, for a move that sets (781,991) and (214, 1), the message would become (hex-encoded):

--                   = The type (0x4D = M in ASCII)
  --                 = Length (8 bytes)
    --------         = 718 and 991 encoded as network-order 16-bit integers
            -------- = ditto for (214,1)

You're probably going to want to write a client. Here's how:

  1. Connect to the central arena server (host life.twnc.org, TCP port 1970).
  2. Send an I​dentification message with an identification string (up to 250 bytes of UTF-8).
  3. Have your bot wait for a game to begin. The arena hosts one game at a time. You will fight either another contestant's bot, or a training round against my entry, which is not included in the competition.
  4. The game starts when you receive a S​tart message. Included in the message is the name of your opponent, which will start with "wandernauta/" if you're up against the training bot.
  5. When you receive a M​ove, apply it to your board. Moves are encoded as arrays of pairs of 16-bit unsigned integers. For each pair, set the cell at that X/Y-coordinate to the enemy's 'color'.
  6. When you receive a G​eneration marker, evolve your current view of the game board one step according to the rules above.
  7. When you receive a T​urn message, it's your turn. Reply with a Move as soon as possible. (Don't want to interfere? Send a Move message with zero moves.)
  8. When you receive a B​ye message, the game is over and you can disconnect. The value will tell you your score and your opponent's, in that order, as a pair of 32-bit unsigned integers.
  9. Reconnect when you're ready for another round.

Note that the server will not send you the entire state of the board at any time for bandwidth reasons. You'll have to keep track of the evolving yourself. (Here are implementations of normal Life in many languages. You could probably base your implementation on one of those.)

Competition rules

  • You should I​dentify as name/bot, where name is your StackExchange user name and bot is a PG-rated but otherwise very intimidating name for your implementation (Glider of Doom? DiveBomber? Pufferfish?)
  • If your implementation fails to follow the protocol, you'll be disconnected - and the game will be forfeited.
  • You are not allowed to willfully take advantage of a fault in the arena server.
  • Have your AI decide on moves in a sane time. Calculate strategies in advance if at all possible so you'll be able to send your next move as fast as reasonably possible.
  • Finally, please be nice to the server. It's there for your enjoyment.
  • Not following these rules can lead to disqualification.


The bot with the largest KD spread, that is, the largest difference between the amount of wins and the amount of losses, wins.

That's great: it makes it clear that it's binary data and shows the endianness. –  Peter Taylor Mar 24 at 23:27
Will the server keep track of the number of wins/losses or are we suppose to do it ourselves? In any case, are we supposed to play against all other contestants? is there a minimum number of games to play to qualify? –  plannapus Mar 25 at 9:13
I haven't experimented with the rules, only thought about whether standard patterns (like the glider) would work with these rules. The strategy you're talking about sounds like a valid strategy - for example, you could plaster the grid with blinkers, but that will 'only' get you linear growth. I'm hoping someone find a strategy that really uses the Game of Life rules to their advantage. –  Wander Nauta Mar 26 at 18:49
Gliders seem useless, due to the dead walls. And is superlinear growth really achieveable with 30 cells per turn and the opponent potentially interfering? If anything goes wrong with your set up you would have been better off just building stable shapes. But as I said, my GoL knowledge does not extend far beyond glider guns. Maybe a torus geometry would actually make it more interesting? Just some ideas... –  Martin Büttner Mar 26 at 19:38
@m.buettner Torus world would be interesting, but I think it would increase the chances of the game just turning into chaos, with a random winner. Take a look at this gif: upload.wikimedia.org/wikipedia/en/d/d1/Long_gun.gif The gun destroys itself. With a wall or infinite field, it doesn't. Infinite field isn't doable, so wall it is. –  Wander Nauta Mar 26 at 19:44
I see, thanks for the examples. I agree with the walls then. Thinking about enemy cells counting for starvation rules could be interesting though. It could also make the challenge way too complex. Unfortunately, I have no real idea how to figure out what's best. Regarding the client/server think, I still think that simply pairing up all contestants on one server to get an equal amount of matches for each pair would be fairest, but I can understand if you don't have the resources for that. (Maybe some other use would be willing to help out with that?) –  Martin Büttner Mar 26 at 20:14
"The bot with the largest KD spread, that is, the largest difference between the amount of wins and the amount of losses, wins." -- does that mean that if we lose every battle, we win the entire tournament? –  Jan Dvorak Mar 27 at 7:49

Let's Play Mafia!

Mafia (also known as Werewolf) is a party game that plays roughly like this:

  • The game begins on day 0. After every day n comes a night n. After every night n comes a day n+1. i.e. D0, N0, D1, N1, D2, N2...
  • At the dawn of day 0, a host secretly chooses players to fill certain roles:  
    • Some number of players become the mafia. Every night, every mafioso chooses a player. At the dawn of the next day, the player chosen by the most mafiosos is killed. They are permanently removed from the game and their role is publicly revealed. Mafia-aligned.  
    • Some number of players become cops. Every night, each cop chooses a player. At the dawn of the next day, the cop becomes aware of that players alignment. Village-aligned.  
    • Some number of players become doctors. Every night, each doctor chooses a player. If this player is the same player that the mafia chose to kill, the mafia's actions for that night are canceled. Village-aligned.  
    • All players who aren't chosen for another role are villagers. Villagers have no abilities that aren't shared by the whole town. Village-aligned.
  • Every day except day 0, the entire town (that is, all living players) votes for a player. At the end of the day, that player is removed from the game and their role is revealed. (On day 0, everyone just chills until nightfall.)
  • If, at any point, there are no remaining mafiosos, the game ends with all village-aligned players victorious (including the dead).
  • If, at any point, the village-aligned players do not outnumber the mafia-aligned players, the game ends with all mafia-aligned players victorious (including the dead).

For this challenge, your goal is to write a bot to beat other bots at Mafia!

I've written a control program for this challenge (available here, but I'd recommend against looking at it because it's pretty gross) for you to test your bots with, but the real judging will go down on my Raspberry Pi. (Sandbox note: Details about the Pi [e.g. what OS I'll use, etc.] will come before this gets posted 4 realz)

How to make a working bot

All you have to supply for me is a file called run. Inside the directory structure where this challenge will take place, your bot will live here:

players/               # You are here!
    some_bot/          # Let's pretend you're some_bot.
        run            # This is what you give me

The run file, when executed, will make your bot do its thing. It's important to note that this file must not require any command line arguments or anything. It will be run exactly as ./run. If you need to be executed in a different way, you'll have to work around it by doing something like this:



# code goes here



./real_bot.py --flags --or --whatever

An important thing to note is that all input your bot receives will be found in the file from_server and the control program will look for your bot's output in to_server. I chose to do it this way so that any language that can do file I/O is able to participate. If your language makes it easier to work with stdin and stdout than file I/O, you may want to write a run file that looks like this:


./real_bot.py < from_server > to_server

This will make it so that stdin comes from the from_server file and stdout goes directly to to_server.

Your bot will not stay running for the duration of the game. Instead, it will be run when it needs to make a decision. Likewise, it will not be informed when it's dead, it just won't be run anymore. Plan for this by saving anything you want to remember to a file and reading it later. You may create, write to or read from any file in your bot's folder, but you may not write or read anywhere outside of that folder, including network access or anything. If your bot knows anything that it wasn't told from inside the folder, or if it touches anything that isn't inside that folder, your bot is disqualified.

How to make a functional bot


At the beginning of the game, the file players will be filled with a newline-delimited list of all players in the game. It will not be updated as players leave the game.

At the dawn of day 0, all players will find this message in their from_server file:

Rise and shine! Today is day 0.
No voting will occur today.
Be warned: Tonight the mafia will strike.

If you are the cop, the line You are the cop is appended to the end. The doctor sees You are the doctor. The mafia sees You are a member of the mafia.\nYour allies are: and a newline-delimited list of mafia members, excluding the player reading the message.

At the dawn of all other days, this message will appear:

Dawn of day `day_number`.
Last night, `victim` was killed. They were `victim_role`.
Investigations showed that `cop_target` is `target_alignment`-aligned.
These players are still alive: `remaining_players`

dayNumber is replaced with the number of the day. victim is replaced with the name of last night's victim, and victim_role is one of:

  • a villager
  • a mafioso
  • the cop
  • the doctor

cop_target is the name of the player the cop investigated last night, and target_alignment is either village or mafia. Finally, remaining_players is a list of players that are still alive in this format: player1, player2, player3

The second line is omitted if there was no kill last night, and the third line is shown only to the cop.

Once this message is out of the way, the day begins! Each bot can make 50 actions throughout the day, where an "action" is voting for a player or saying something out loud.

To vote for a player, write vote player_name to your to_server file and terminate. To vote to not kill anyone, write vote no one. When you vote, all players (including you) will see your_bot votes to kill your_selection. Votes are ignored on day 0.

A number of pre-defined messages can be sent to all players. The id of each possible message is listed here:

 0: No
 1: Yes
 2: I am the cop
 3: I am the doctor
 4: I am a normal villager
 5: I trust this player: 
 6: I think this player is suspicious: 
 7: I think this player is the cop: 
 8: I think this player is the doctor: 
 9: I think this player is a normal villager: 
10: I think this player is mafia: 
11: Do you think this player is mafia? 
12: I tried to save this player: 
13: I successfully saved this player: 
14: I investigated this player and found that they were mafia-aligned: 
15: I investigated this player and found that they were village-aligned: 
16: Will you please use your power on this player tonight?

All of these messages except the first five are referring to a specific player. To say one of those messages, write say message_id player_name. For one of the first five messages, just write say message_id. You may add an optional third argument to both of these, specifying the name of a player you're talking to (all players can still read it, but they'll know who the intended recipient is).

When your bot says a message, all players read your_bot says "message", where message is the message associated with the id you wrote. If the message includes a subject, one space character and the subject are inserted directly after the end of the message. If it includes a recipient, their name, one colon and one space character are inserted immediately before the message.

At the end of the day, all living players are run one last time to see the result of the vote. If a player was voted out, this is written:

The town has killed player_name!
They were a villager

... or a mafioso, or the cop, or the doctor.

If no player was voted out, this is written instead:

The town opted to lynch no one today.

When the controller sends these messages, it ignores any response from players. The day is over.


At night, everyone but the villagers get to use their power.


You will read It is night. Vote for a victim.. When this happens, output the name of the player you'd like to kill.


You will read It is night. Who would you like to investigate?. When this happens, output the name of the player you'd like to check.


You will read It is night. Who would you like to save?. When this happens, output the name of the player you'd like to protect.

After this, the next day begins as normal.

General Information

  • The game will not run without 6 or more players.
  • One third of the players, rounded down, will be mafia. One player will be a doctor, and one player will be a cop. All other players are villagers.
  • Ties in the village vote or the mafia's overnight vote are settled randomly.
  • Bot names must be alphanumeric + dashes and underscores.
  • It is forbidden to use knowledge of opponent's code directly. In theory, I should be able to put your bot up against bots you've never seen before and have it perform comparably.
  • Regrettably, if I can't get your program running using exclusively free (as in beer) software, I'll have to disqualify it.
  • I reserve the right to disqualify any submission if I believe it to be malicious. This includes, but is not limited to using excessive abouts of time, memory or space to run. I've intentionally left the limit soft, but remember: I'm running this on a Raspberry Pi, not a supercomputer, and I don't want getting results to take a year. I don't expect to have to use this, since my standards are pretty low. This is basically "if I think you're being a dick on purpose", and if you can convince me otherwise I'll reverse my decision. (Sandbox note: Am I allowed to do this? It's less than "objective" for sure but really it's just going to be a fallback "don't be a dick" rule. If not, what should I say instead?)


Each round, 100 games will be run (this may increase as more bots join to keep the sample size large enough, but in theory that won't affect anything). I will record how many times each bot wins as a villager compared to how many times it plays as a villager, and the same for mafia. A bot's villager_ratio is number of games won as villager / number of games played as villager, and mafia_ratio is the same but s/villager/mafia/g. A bot's score is (villager_ratio - mean villager_ratio) + (mafia_ratio - mean mafia_ratio).

Example bot

Randy the Robot is not a good mafia player. Randy ignores pretty much everything, randomly choosing what to say, who to vote for, and who to target with night powers.



./randy.py < from_server > to_server



import random

with open('players') as f:
    p = f.read().split() + ['no one']

day = True
    line = raw_input()
    if line.endswith(('?', 'victim.')):
        day = False
    if not day:
        print random.choice(p)
        if random.random() > 0.5:
            if random.random() > 0.5:
                print 'vote {}'.format(random.choice(p))
                id = random.randint(0, 17)
                print 'say {}{}'.format(id, (' ' + random.choice(p)) if id > 4 else '')
except: pass

(Sandbox note: I can't shake the feeling that I've forgotten something. Hm. Probably going to be mad when I figure out what it was :P)

Just an idea: Wouldn't it be easier to make the bot to be communicated by stdin/stdout? I mean: recieve line-by-line the messages from others and from the system (things like: DAY begin, NIGHT begins, KILLED xyz, SENTENCED uvw, MESSAGE 5 abc SAID klm, ...)? It would be IMHO easier to control such program, because it would be run only once, so I (as a bot owner) could easily remember things and stuff. –  tohecz Jun 9 at 14:33

Waving Hands bot

This is a sketch for a contest for a game which is much more complicated than the previous questions in this genre. Implementing the test framework will be a lot of work and it will require a lot of debugging, so I want to get feedback on whether the game is too complicated before I start work on that.

Waving Hands (original known as Spellbinder) is a two-player simultaneous-turn-based strategy game. At one level it is quite simple. You have two hands. Each turn you perform an action with each hand. Sequences of actions performed with the same hand create spells, which have varied effects.

The first level of complication comes from the number of spells: 42. I don't intend to reproduce a list: there is an online rules page (which is backed up by archive.org should that fallback be necessary).

The second level of complication comes from the interactions between the spells. This is where debugging of the test framework is most likely to be needed. My plan is to allow complaints about the framework's implementation of the rules for a period of two or three weeks or until there are three posted answers, whichever is the later.

At each turn the bot will be provided with a full history (except for moves which the rules say it can't see, which will be so indicated). However, it will not be provided with any other identifying information about its opponent. I think that it will be hard to fingerprint some bots, although probably not all.

The framework will probably be written in Java and hosted on github. I intend to provide one or two wrapper classes for non-JVM languages, and a "bot" which brings up a UI for human play, which will be useful for debugging and testing your own bot.

Under the label of fair play, it will be forbidden to attempt to interfere with the opponents or access their memory. A bot may store information about the current game, to save recomputing it each move, but it may not persist information between games. Competitors may submit more than one bot, but they must be independent: i.e. no submitting bots whose purpose is to help your favoured bot win.

To reassure anyone who's worried about copyright: the creator of the game has stated

I retain full rights to the game, and if any commercial incarnation appears then I want a royalty! I have no objection to people implementing or running derivatives of the Spellbinder so long as they make no money from it, though.

Normally upvotes in the sandbox indicate that you think the question is ready to post. This one clearly isn't. However, please upvote it if you think that the outlined proposal would make a good question. If there's enough support, I will create a separate sandbox answer when the test framework is ready for early criticism.

@Geobits, I believe in updating the accepted answer when a better answer comes along. –  Peter Taylor Apr 9 at 14:14

Six Miscellaneous Question Ideas

These are a few of my lingering ideas for questions. I am not planning to post them myself so anyone else is free to post, revise, update, do anything to them. That why this is a community wiki. I will not be updating them further. (Feel free to move them into separate answers if desired.)

None of them are finalized, they still need some details filled in. I don't claim that any are superb, they just pique my interest. They are roughly arranged in most complete to least complete.

[Things in bracketed italics are my meta-notes, they are not part of the challenge.]

Drawing in Slashes

Posted by me

Counting Rice

Here is an image of 96 [iirc] grains of rice laid out flat on on a green background.


I have a number of similar images with the same background that have anywhere from 100 to 1000 grains of rice laid flat in them. [I actually don't have these images. This is the only one I took. If I we're really doing this I would post at least 4 test images and use 10 or so other images for scoring.] Write a program that can take such an image and accurately count the number of grains of rice.

The algorithm that can most accurately count the grains in the 10 test images (which will not be distributed until the contest is over) will win. Your score is the sum of the absolute differences between the actual values and your algorithm's values for the 10 test images.


  • No hardcoding output.
  • The background is always a plain uniform color. [Not true in the image above. The shadow gradient and textured green are not ideal.]
  • All sizes of grains should be counted as one grain.
  • The grains are not guaranteed to be uniformly distributed in any way.
  • Only white rice is used.

[This could work for any discrete grain-like object. My image is only a (bad) example. Yours may look different (and needn't be green). The precise number of grains in each image should be known.]


Posted by me :)

Catenary Between Two Points (Hanging Chain)

Claimed by Von Ilya

Family Tree Solver

Claimed by Martin Büttner

Go with the flow

Consider a grid made up of the characters ^v<>O (the last one is uppercase O), such as:


The ^v<> represent hills in a landscape whose downhill side is the direction the "arrows" point. The O represents lakes in valleys between hills.

Suppose 1 "unit" of rain fell over every character in the grid (18 units above). How much rain goes to each O? How much goes out of bounds?

Write a program that calculates this. You may assume the grid has no cycles, all the rain will end up in a lake or out of bounds. (so >< is never input).

The output should be in this format (output for example shown): (OOB = out of bounds, (a, b) = lake at (x, y))

OOB: 4
(1, 1): 6
(2, 1): 5
(5, 1): 1
(4, 2): 2

I/O could be from stdin/stdout or files or both.

[Could do periodic boundary conditions.] [Could allow cycles and have period2cycle: amount be in output.]

[I can't believe something like this hasn't been posted before. Maybe it has...]

I like the rice one just because I'd like to see how people would approach it. –  Beta Decay Aug 21 at 12:58

Conquer the Solar System

Here is an outline for a strategical King-of-the-Hill challenge which is loosely based on Risk (loosely enough so as not to preclude a future Classic Risk KotH).

It is far from complete, but I'm posting it here to gather feedback from the community to finalise the rules before getting down to implementing the control program. This would definitely make for one of the more complicated KotHs and I'd like it to be as fun as possible, so that it's worth the participants' time! I will probably leave this up for several weeks before starting work on the controller.

I wanted to try something new: The distinguishing feature of this challenge is that it does not use simultaneous turn-based simulation, but rather something similar to Final Fantasy X's Conditional Turn-Based Battle system. Different actions take different amounts of time, and it's simply your turn again when that time has elapsed. Of course, the control program will simply skip ahead to the next scheduled event.

There are probably more technical details in this post than what will be necessary for participants of the final challenge (and will most likely be presented in a different form then). I just wanted to include everything I've currently got, so people might point me towards issues in the underlying assumptions.

The Setting

The year is 2200: Mankind has spread out over the entire solar system. But we all know how much humans like other humans with different resources – interplanetary war has broken out. Each inhabited planet or natural satellite – collectively referred to as (celestial) bodies – starts out as one faction in this war. The goal is conquer as much of the solar system as possible.

The Model

The arena of the challenge is hence the solar system. I will include all solid planets and natural satellites with a diameter of 10 km or more (just for a bit of realism; this should provide a large enough surface area to build a base). There are 89 of those bodies – I could add even smaller objects should I get more submissions than that, but I think that's near impossible.

Note: I said "solid" bodies. Jupiter, Saturn, Uranus and Neptune are gas giants and hence cannot be landed on (their satellites can be, though).

Planetary motion will be simulated, although in a simplified manner. Orbits are assumed to be circular and lie all in one plane, with a radius of approximately their real-life semi-major axis, and their real-life orbital period. Hence, no gravity is simulated – only simple (uniform) circular motion.

Satellite motion will not be simulated. Travel distances between satellites or between a planet and its satellites are assumed to be fixed (and will be determined once, by me, dependent on the satellites' orbit sizes).

The asteroid belt between Mars and Jupiter can be travelled to, but no bases can be built there – it acts mainly as a hideout. It is modelled as a continuous ring at fixed distance from the sun with fixed orbital period. Bots can choose to land their units at any position on the belt. Individual asteroids are not modelled – not even the larger ones like Ceres, which are way above the size limit.

Technically, the map is a complete graph whose vertices are the above 89 bodies plus the asteroid belt. The travel times between any pair of bodies depends on their distance at the time the travel commences (neglecting motion of the target during the travel). As planetary motion is simulated these travel times do generally change over time though. The future spacecraft is assumed to travel between 500,000 and 1,000,000 m/s and travels in straight lines, giving time scales between 10 seconds and 80 days.

For each match, the solar system will start out in a random configuration (each planet getting a random position on its orbit). Of course, that's not realistic, because the planetary configuration for 2200 is not going to be subject to change, but we need to keep the game fair.


  • Each player starts with a base on a random body. The remaining bodies will be uninhabited.
  • Each player starts with one flagship, and n fighters (where n needs to be determined, but I'm thinking on the order of 10) – collectively referred to as units.
  • Players write a bot that is asked for a move whenever one of their own units is idle or needs to act, because it's being attacked or similar.
  • Fighters are a lot faster than flagships, so they will act as scouts as well, to avoid time-wasting travel with the flagship.
  • Flagships can build new bases on uninhabited bodies, or take over enemy bases (the former taking longer than the latter).
  • Each additional base immediately grants another n fighters.
  • Each base regularly spawns new fighters (say, once a week). If a player controls an entire planet system (the planet and all satellites), the spawn rate on all bodies in that system is increased (to, say, once every five days).
  • Flagships are vulnerable while working on bases. Either they can't interrupt the building process upon arrival of enemies, or such an interruption will cause the total build time to increase.
  • Upon landing on a body, units can't leave immediately. They need to remain for p % of the time it took to get there (p ≈ 10?) in order to refuel. Technically, this is to prevent units from hiding all the time in interplanetary space. (formula subject to change)
  • If there are units from multiple players on a body, they may engage in combat (see next section for details on combat).
  • If a player's flagship is defeated they immediately lose the game! All their units and bases go over to the player who killed the flagship.
  • The bot may always decide to wait idly (I'll set a minimum on this, to prevent bots from spamming the control program with millisecond waits). Waiting will be interrupted by any relevant event like allies or enemies arriving somewhere.

Combat System

  • Fights are carried similar to the rules of Risk. Please refer to the Wikipedia page or the internet for the exact rules for now – all necessary rules will be part of the final challenge post though.
  • Attackers may choose to attack with 1 to 3 units, defenders choose to defend with 1 or 2 units. The outcome is determined by rolling dice. After each round of battle, battle may either continue with the remaining units or be aborted.
  • One round of combat takes 1 day. (subject to change)
  • Whether a player is attacker or defender depends on whether he has a base on the current body. This means that two attackers could be fighting each other on an unclaimed body, in which case both may use 3 units in a fight, but units from both sides die in a tie.
  • If a player has a flagship on the body where the fight takes place, one unit will roll a d8 instead of a d6, unless they are currently working on a base (building one or converting one).
  • When players lose units, they always lose fighters first. Hence, if a player has a flagship on a planet, and loses less than all of his units, the flagship will remain.


I will either go with Rusher's approach of writing a Java controller where participants only need to implement an interface (and provide a wrapper for non-Java submissions) or I'll write a controller that invokes bots as separate processes whenever its their turn.

On their turn, each bot will be provided with

  • the current time
  • the number of bases and units controlled by each player
  • the state of all bodies the player currently has units or bases on
  • the ID and location of the idle unit(s) that can currently perform an action
  • a list of all bodies with their current positions (in Cartesian coordinates, so distances can easily be determined)
    • potentially I'll just provide a list of travel times for each idle unit instead, to save the bots the need to compute those
  • a list of all bodies with their current angular positions

The latter can safely be ignored, but is provided for bots that want to predict planetary motion to take shortcuts. Static numerical data like orbital radii and periods will not be provided to the bots, but I'll publish a table with the challenge to be hardcoded into the bots if desired.

Further Design Decisions

I realise that there is a lot of complexity in this. This is why I need your help to refine the concept and remove unnecessary details while keeping the heart of the challenge in tact (while making sure the rules are consistent). Please give me all the feedback you can think of, but here are a few particular questions I have in mind that need to be answered:

  • How should vulnerability during base-building be modelled? By penalising or by disallowing interruptions?
  • How can fights between more than two parties be handled?
  • Is the "refuelling" necessary/useful? Do the details for it need work?

In any case, I don't doubt this challenge will remain fairly complex when finalised. It might help to gather some momentum if a few heroes volunteered up front to submit a bot to this - ideally ones which show that the entry barrier doesn't need to be as high as it looks.

Anyway, thanks a lot for reading this and helping out with the design of this challenge!

I'm happy to discuss details in chat (The Nineteenth Byte or Golf/Puzzle Lab; but ping me so I know you've posted there) or just here, but this challenge may need more discussion than fits in comments.


Good Versus Evil (Posted)

Illustration drawn by brother Illustrated by Chris Rainbolt, my brother and a fresh graduate from Savannah College of Art and Design


Sort characters by darkness

How should we treat anti-aliasing? As fully-filled, as partially-filled, or do we need to use a rendering technique / font that aliases the letters? –  Jan Dvorak Mar 5 at 6:07

KNOT or NOT? (posted)

Another good link is the specific page for the Unknotting Problem. –  Geobits May 29 at 14:28

Survival Game - Create Your Wolf (Posted)

Limiting the answer to Java only will eliminate quite a large portion of the people who'd like to solve your puzzle. –  Wander Nauta Mar 20 at 19:22
For non-Java entries you could supply a wrapper Wolf which uses ProcessBuilder to execute an external program. –  Peter Taylor Mar 20 at 23:23
@PeterTaylor That's a wonderful idea. That way, the wolf itself is atomic and the structure of my control program doesn't have to change one bit. Thanks! –  Rainbolt Mar 21 at 2:03
@Rusher no this explanation is very clear thank you. I guess the proper tag will then be king-of-the-hill rather than the generic code-challenge. And I will definitely play (granted that other languages than java are also accepted :) ), sounds like a great challenge. –  plannapus Mar 21 at 13:03
Hmmm. I think the "one-on-one" part of the 'king-of-the-hill' concept is maybe too narrow. Seem to me the most important part of the concept is the fact that the scripts are played against one another and that the winner is the one that defeats the others. But that's just my opinion. As far as the changing letter is concerned, it seemed relatively simple to me but ok. –  plannapus Mar 21 at 13:10

Magrathea 2.0 - Building Mountains [Posted]

With the big crash of the universal economy also the demand for custom made planets plunged. The Magratheans had to look after more steady revenues also from a broader class of customers. Therefore, they invented the have-your-own chain of mountain (or short havoc-o-mountains) for people with smaller budget who could not afford a complete planet.

The mountains are build according to the customer's plan (a.k.a. strings of digits and dots) and delivered using ascii-art (consisting of , /, \, ^ and v).


Write a complete program which takes input (single string) either from STDIN or as argument and outputs to STDOUT. This puzzle is a code-golf so please show some attempt at golfing.


A string of dots and digits providing the basis for the mountain chain. Each string is exactly as long as necessary to support the mountains and each peak is given by a digit instead of a dot, indicating the height of the peak.


An ascii version of the mountain chain. - Each digit in the input represents exactly one peak (^) at exactly the height indicated by the digit. There must be no additional peaks in the output (i.e. at places where there is a dot in the input). - Mountains are of triangular shape, i.e. slopes are created using / and \ characters. - Passes where two mountains overlap are shaped using the character v.

You may assume that the input provided is valid, i.e. there always exists a solution according to the rules (e.g. an input of 13.. would not result in a valid configuration and may be ignored). Moreover, on each side there are exactly as many dots such that the mountains must no be cropped.


The first line shows the input, all other lines constitute the desired output. (Actually the mountains look much better in my console than here)



^/ \

 ^/ \
/    \

 ^ / \
/ v   \

  / \  ^   ^ 
 /   \/ \ / \
/        v   \
@Howard Does that mean that 9 is the highest height? –  Quincunx Dec 30 '13 at 1:35
@Howard I think you should. –  SQB Jan 15 at 14:52

BlackJack (or Twenty-one, whichever)

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


I would be delighted to write some, some of the framework can be derived from my work on the TPD scorer. I just wanted to get some reactions to the idea from mods etc.

Clear Rules

  • perfect/ideal hand has a score of 21
  • all face cards have a value of 10
  • all numeric cards are worth their number
  • aces are worth 11 or 1. this will be dealt with automatically by the framework, not the bots.
  • scores in excess of 21 which use an ace as 11 force the ace to reduce in value to 1
  • scores in excess of 21 which cannot be coerced below the threshold of 21 "bust" the bot

General Ambiguities

  • is the addition of betting too much?
  • how to handle decks and seating? - obviously multiples of the standard 52-card deck will be used rather than random values, but should all the bots play at one table, dealt to from about (n/6) decks, or should they be split into 5-6 bot tables which must be shuffled?

Programmer's Interface

I like the argv-only input from TPD, besides it's easy to implement. 1. argv[1] - your hand as a string say "KJ" in caps, where each letter is the first letter of a card in your hand. So for "KJ", the bot's hand is King, Jack therefore score is 20. 2. argv[2] - known cards on the table - the letters of all cards which the bot could see without cheating. 3. argv[3] - total number of cards dealt (integer as string)

Winner Selection

The winner would be the author of the statistically most successful bot, as determined by the bot's average probability of winning a round. Duplicated bots will be DQ'd, and copied strategies are frowned on.


- Formatting fix (4-4-2011)

Basic Markdown Parser

Write a script or function that parses Markdown. These rules must be parsed:

  • `foo`<code>foo</code>
  • *foo*<em>foo</em>
  • **foo**<strong>foo</strong>
  • ***foo***<strong><em>foo</em></strong>
  • _foo_<em>foo</em>
  • __foo__<strong>foo</strong>
  • ___foo___<strong><em>foo</em></strong>
  • [foo](http://bar)<a href="http://bar">foo</a>
  • [foo](bar)[foo](bar)
  • ![foo](http://bar)<img src="http://bar" alt="foo"/>
  • ![foo](bar)![foo](bar)
  • # foo<h1>foo</h1>
  • ## foo<h2>foo</h2> (and h3,h4,h5,h6)

- unordered list:

- foo
- bar
- baz

                                             ⇓                        ⇓                        ⇓


- ordered list:

1. foo
47. bar
22. baz

                                             ⇓                        ⇓                        ⇓


- code block:


                                             ⇓                        ⇓                        ⇓


- blockquote:

> foo
> bar
> baz

                                             ⇓                        ⇓                        ⇓

<blockquote>foo bar baz</blockquote>


  • <b> is not the same as <strong>
  • <i> is not the same as <em>
  • you don't need to parse
    • [1](http://) and [something][1]
  • parse left to right and close before opening, e.g.
    • *Strange **String*here** -> <em>Strange </em> <em>String</em>*
    • note that the mismatched * got passed through without rewriting* This ** is * wrong ** should compile as

You can assume you'll never receive:

  • nested lists
  • code/blockquotes in lists (they end the list)
  • two spaces at the end of a line
  • horizontal rules (<hr>)
  • HTML can be passed through directly (trust the user)


It's code golf; least bytes wins.

-5 for a detailed explaination


I would like to provide some way to test it. I'm thinking I can make a fiddle that takes the generated HTML as a text-box input for a test document, and compares the DOM. I'll try to write up a test document.

This question is quite massive. Feel free to make edits to optimize it. It can always be rolled back, so be brave.

Are __underscore__ variants of the **asterisk** versions needed?


Draw the € sign (posted)

I think it takes 4 steps: one to set the mask, one to draw the circle, and two to draw the parallelograms. Although it might be shorter to do it as a single SVG path. Either way, graphical-output challenges need to specify some kind of minimum size and quality restrictions (and if you want something other than hardcoded SVGs it's not a bad idea to take a scale factor as input). –  Peter Taylor Apr 22 at 15:07

Evolution of Squares!

This is an idea for a question, and is very much unfinished. Please help me develop it further.

This is inspired by an evolution simulation I coded a few years ago in JavaScript. The source code and documentation can be found on GitHub, and you can play the simulation itself here.

This will be a . I'll provide a specification which all answers must keep to and a few ideas for features, but otherwise add as many features as you can.


Your task is to build a simulation which demonstrates evolution by natural selection ("survival of the fittest"). The world in which this will be carried out will be a two-dimensional, n by n (exact dimensions to be decided) grid. Each cell on the grid can be empty or occupied by a living cell (or by food resources?).

Cell lifetime

Cells have a 'lifetime counter', which starts at some value when the cell is born and diminishes randomly over cycles of the simulation, so the cells age. It can be replenished by food, but when it reaches 0, the cell dies and is removed (or converted to a food block).

Cells instantly die when completely surrounded? Is that a good idea?


Every so often, cells replicate - produce a copy of themselves, with the lifetime counter reset to maximum, normally with identical characteristics.

There is a probability p (to be decided) that when a cell is replicating, its genome will be changed. It can "improve" or get "worse" with equal probability.

The genome can be as simple as an array of true/false booleans for different characteristics, or an array of integers/decimals describing how much of a characteristic there is (e.g. replication per 100 ticks).

Characteristics which could be included are:

  • faster replication
  • eating other cells to increase lifetime counter
  • movement

The Simulation

The simulation starts with a single, very basic cell, with no fancy characteristics, placed at the centre of the grid. If we decide to implement food resources for cells to pick up, some of these will spawn as well.

Every cycle, cells replicate, age, and die as described above.

There are a wide variety of examples of artificial life out there. Since it's a popularity contest I think there will naturally be variety in the answers. The main thing is to specify the restrictions if you don't want it too open ended... Presumably the length of the code will be restricted as it has to be posted into the limits of a single answer? –  githubphagocyte Jun 7 at 1:35

King of the Hill- Simple RPG


Your challenge is to make a bot that plays a simple RPG game against other bots.

The Rules of the Game

The Board

The board is a 500x500 2-dimensional array of cells. In any cell, there is one of the following:

  • Nothing.
  • An obstacle. Cannot be occupied by anything.
  • A player.
  • A monster.


Each turn, a player can:

  1. Move: you can move north, east, west, or south, or not move at all. Attempting to move into an obstacle, or off the edge of the board, will result in you not moving at all.
  2. Perform a special attack: you can either perform a ranged attack, an area attack, or no special attack at all.
  3. Battle: if you encounter an enemy, you can fight them.


Whenever you enter a square that is already occupied by a monster or another player, you fight them. You and your opponent take turns attacking each other, with the first move being decided randomly. At any point in the combat, you may flee. Also, once per battle, you may use a special attack which does double damage.

Damage is calculated using this formula:

Damage = Attacker's attack modifier + Random number from 1 to 5 - Defender's defence modifier

Special Attacks

There are two special attacks: A ranged attack, that targets any enemy within 5 squares, and an area attack, that targets all enemies within 2 squares. Damage is calculated using the same formula as for melee damage.


In the game, there are 5 monsters:

  1. Goblin. Attack: 1; Defence: 1; HP: 1; moves randomly; 1XP for killing.
  2. Orc: Attack: 3; Defence: 2; HP: 5; follows players; 5XP for killing.
  3. Troll: Attack: 5; Defence: 2; HP: 10; moves randomly; 10XP for killing.
  4. Giant: Attack: 10; Defence: 5; HP: 15; follows players; 50XP for killing.
  5. Dragon: Attack: 20; Defence: 10; HP: 20; follows players; 100XP for killing.

If you kill another player, you receive 100XP.


When you create your bot, you must give it 5 attributes. They are:

  • Attack: your attack bonus when using a melee attack.
  • Ranged Attack: your attack bonus when using a ranged attack.
  • Area Attack: your attack bonus when using an area attack.
  • Defence: your defence bonus.
  • Constitution: added to your HP (10 by default). Note: If your bot's constitution is -10, it dies immediately.

These attributes must sum up to 12. They may be anywhere between -10 and 22.


public class MyBot extends RpgBot
    public static final int ATTACK = <insert here>;
    public static final int RANGED_ATTACK = <insert here>;
    public static final int AREA_ATTACK = <insert here>;
    public static final int DEFENCE = <insert here>;
    public static final int CONSTITUTION = <insert here>;
    // you can add something here
    public MyBot() { super(); }
    public Move move() {
        // insert here: return either Move.NORTH, Move.EAST,
        // Move.WEST, Move.SOUTH, or Move.NO_MOVE.
    public SpecialAttack makeSpecialAttack() {
        // insert here: return either SpecialAttack.RANGED,
        // SpecialAttack.AREA, or SpecialAttack.NONE.
        // For ranged attacks, use setTargetX() and setTargetY()
        // to set the target beforehand.
    public Attack attack(Entity m) {
        // insert here: return either Attack.NORMAL,
        // Attack.SPECIAL, or Attack.FLEE.
        // Entity m is one of the monster entities.

Here are the additional functions you get for your convenience:

Entity surroundings(int x, int y)- returns an entity representing what is located at that point. x and y range from -5 to +5, with 0, 0 being the square where you are. Trying to access outside that range will result in an Exception being thrown. Entity is one of:

  • Entity.NONE- nothing.
  • Entity.OBSTACLE- an obstacle or the edge of the map.
  • Entity.PLAYER- either you or another player.
  • Entity.GOBLIN- a goblin.
  • Entity.ORC- an orc.
  • Entity.TROLL- a troll.
  • Entity.GIANT- a giant.
  • Entity.DRAGON- a dragon.

At the beginning of the game, the field is randomly populated with 300 obstacles, 1000 goblins, 500 orcs, 100 trolls, 50 giants, and 10 dragons.

void setTargetX(int x) and void setTargetY(int y)- set the target x and y indexes of the ranged weapon. Indexes range from -5 to 5, with 0, 0 being your location. Passing these functions an index outside the range will result in an Exception being thrown.

Winning Condition

The winner is the bot that acquires the most XP before it dies.


Global Warming

This KOTH takes place on a melting iceberg. You must stay on it as long as possible, and preferrably, be the last man standing.

The field is a perfectly circular iceberg which shrinks at a unknown rate, in the center of a 2D plane. Gameplay is executed in turns on which your program will be called with the current status of the iceberg and other participants. Each turn you may either change your movement direction or push someone near you (or neither).

Movement and positioning

Positioning is in a 2D plane of floating point coordinates, and movement is a speed of x and y components. When issuing a move command, your entry will keep moving in that direction until you explicitly tell it to stop or change direction with another move command (or a push, more on this soon). The maximum move speed is 1.0 in magnitude, and if you ask to move further than that, your speed will be adjusted to conform this limit.


Your program can issue push commands to any entity within a radius of 1 from you, resulting in you and your target having your speeds changed to point away from eachother and at a given speed. The push speed is directly adjustable, but the direction isn't. Push speed is under the same limitations as a move command, and thus can't be stronger than 1. If two people push the same target at once, the target is pushed in the resultant direction. Pushing will take into account the target's move command, if there was one.


Each round, your program will be invoked from the command line, with a CSV document being passed to its STDIN. The first line of this document provides the current iceberg radius (floating point number) and the amount of remaining competitors (integer)

After this "header", there will be one line for each remaining competitor in the following format (which is on its turn on the format type(variable)):

string(entity id),float(x),float(y),float(velocity x),float(velocity y)

Your entry will always be the first item on the list.

Example input:


(the \ is a trailing newline, represented like that for clarity)


Your program will process the given input and output a ASV (Anything Separated Values) document. A ASV is like a CSV, except everything that doesn't match the regex [.0-9a-z] is considered a separator (even uppercase letters). If your program emits more than 1 line, only the last one is considered.

For movement:

move,float(velocity x),float(velocity y)

For pushing:

push,string(entity id),float(strength)

To do nothing, simply don't output anyting

Where move and push are string literals.





The following lines are valid outputs for your program:


Detailed Rules and remarks

A list of important points to consider:

  • You can skip your turn by returning no output, but this will make you keep moving in the direction you ere headed to.
  • If a competitor loses, it will not show up on the participants list (see below)
  • A player is considered to fall from the iceberg if their distance from the center is greater than the iceberg's radius.
  • Entries do not have a physical radius, so they cannot bump on eachother (except for the push command)
  • You can't know the shrinking rate of the iceberg.


A entry's score is the average turns_survived*players/total_turns out of 10 runs. Each run may have a indefinite (but not infinite) amount of turns, until only one competitor survives.

The scores will be periodically maintained here, and 100% up-to-date at INSERT URL

The winner will be chosen at INSERT DATE

Examples in pseudocode

Antisocial - pushes everyone away from him, doesn't care about where he is.

#!/bin/env pseudocode
data = read_csv(stdin)
foreach line in data.range(1,data[0,1]):
    if distance(me, line[1], line[2]) <= 1:
        write_csv_line(stdout, ["push", line[0], 1.0])
Well you could also minimise its utility by making it more physically correct such that the push is applied to you as well (in the opposite direction)... conservation of momentum and such. Then you could let players choose the push strength, and they'd have to decide how strongly they want to be pushed themselves. –  Martin Büttner Jul 26 at 13:32
One issue that isn't addressed is what happens to me after I was pushed. If I try to move and one or more people push me, where do I move? What if player A pushes B pushes C pushes A? Also, since you give a speed (but not distance) moved, you should list how much time is simulated between turns (1 second?) –  Zaq Jul 29 at 1:07
@justhalf I didn't want to do that because I had no idea how to, but i just realized it's dead simple to do. Sum the forces and cap to the max speed –  Kroltan Jul 29 at 13:14

Ruby on Rails

You are Ruby, a railway engineer. Your task is to lay track to visit every station in any given valley. The amount of track laid is not important so long as it doesn't cross its own path. There are a couple of other constraints: mountains(^) are impassable so you must go around them, and rivers(~) must be crossed using a bridge(X). You can enter a station(M) from any direction but must exit in a different direction (ie no backtracking).

You have a selection of track to choose from: - | / \ , and in order for the track to be considered complete each piece of track must be adjacent to a previous piece of track or the entrance/exit(>) (Diagonal will be considered adjacent for this question).

Input will be via STDIN and you can assume that all cases will be rectangular and will be solid at all points on the perimeter except for the entrance/exit.

Winner is the shortest code.


# - Valley edge (impassable)
^ - Mountain (impassable)
M - Station
~ - River
> - Entrance and exit point of the valley

X - Bridge
- - Track(East-West)
| - Track(North-South)
/ - Track(SW-NE)
\ - Track(NE-SW)

Test cases

#    M   #
#   ^    #
>  ^^  M #
#    ^   #
# M      #
#       M#

#               #
#  M          M #
#       ^       #
#        ^ M    #
#~~~~~~~^       #
#               #
#   ^           #
#   M^          #
#    ^          #
> ^^^          M#
#        M      #

Possible solutions to test cases

# ---M   #
#/  ^ \  #
>  ^^  M #
#\   ^ | #
# M     \#
# |-----M#

#               #
#  M----------M #
#  |    ^    /  #
#  |     ^ M-   #
#~~X~~~~^  |    #
#  |        \   #
#  \^        \  #
# --M^        \ #
#/   ^         |#
> ^^^          M#

1P5: Iterated Prisoner's Dilemma – Posted


What do you see in an inkspot? Rorschach generation.

It seems pretty good. –  hosch250 Mar 11 at 16:57

1P5: Earthquake! - [Posted]

USGS's seismometers have just detected a major earthquake! Emergency response teams need a quick estimate of the number of people affected. Write a program to compute this estimate.

Your program receives 2 inputs. The first is the details of the earthquake itself. The earthquake modeled as a line segment along which the earth ruptured, along with the critical distance from the fault within which damage could be expected. The second input is a list of the location and population of cities in the area. Your program should compute the number of people living in the affected area, that is the sum of the population of all cities within the critical distance of the fault segment.


First a line describing the earthquake, containing the x,y coordinates of the start and end points of the fault, plus the critical distance. The format is A_x A_y B_x B_y D. For example:

3.0 3.0 7.0 4.0 2.5

encodes the fault extending from (3.0,3.0) to (7.0,4.0) and a critical distance of 2.5.

Second, one line per city in the area, containing the x,y coordinates of the city and its population. For example:

1.0 1.0 2500
5.0 7.0 8000
3.0 4.0 7500
9.0 6.0 3000
4.0 2.0 1000

enter image description here


The number of people living in the affected area. For the above example only the third and fifth cities are in the danger area, so the output would be


Shortest code wins.


Email validation


http://codegolf.stackexchange.com/questions/6535/program-in-python was a bad question, but the underlying challenge of validating an e-mail address is actually quite interesting and has quite a bit of potential for golf. I would expect the winning answer to use a mixture of regex and network libraries.



Tennis Scores {Posted}


Happy birthday to Me - Posted!

Did you mean the Gregorian calendar? If not, you'll need to link to a page which describes the Georgian one. –  Peter Taylor Feb 14 at 10:02
I mean the one they use down in Georgia. –  ugoren Feb 14 at 14:06
Congratulations on 1000th meta post! :P meta.codegolf.stackexchange.com/a/1000 –  Doorknob Feb 15 at 14:33
Thanks, @Doorknob. Where do I get my iPad? –  ugoren Feb 15 at 16:38
Gregorgian? Should be either Gregorian or Georgian, but not Gregorgian. Further, as it is, rule 3 is contradicting rule 2. –  Victor Feb 15 at 18:43

Calculate practical numbers



You must log in to answer this question.

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