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

Sandbox FAQ


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

Write your challenge just as you would when actually posting it, though you can optionally add a title at the top. You may also add some notes about specific things you would like to clarify before posting it. Other users will help you improve your challenge by rating and discussing it.

When you think your challenge is ready for the public, go ahead and post it, and replace the post here with a link to the challenge and delete the sandbox post.


The purpose of the sandbox is to give and receive feedback on posts. If you want to, feel free to give feedback to any posts you see here. Important things to comment about can include:

  • Parts of the challenge you found unclear
  • Comments addressing specific points mentioned in the proposal
  • Problems that could make the challenge uninteresting or unfit for the site

You don't need any qualifications to review sandbox posts. The target audience of most of these challenges is code golfers like you, so anything you find unclear will probably be unclear to others.

If you think one of your posts requires more feedback, but it's been ignored, you can ask for feedback in The Nineteenth Byte. It's not only allowed, but highly recommended! Be patient and try not to nag people though, you might have to ask multiple times.

It is recommended to leave your posts in the sandbox for at least several days, and until it receives upvotes and any feedback has been addressed.


Search the sandbox / Browse your pending proposals

The sandbox works best if you sort posts by active.

To add an inline tag to a proposal, use shortcut link syntax with a prefix: [tag:king-of-the-hill]. To search for posts with a certain tag, include the name in quotes: "king-of-the-hill".

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

4706 Answers 4706

7 8
10 11

ASCII ART edge detection

As the title says, I was thinking to contest in which one must detect edges of an ASCII art.

The code should accept a B/W ASCII art as input. A B/W ASCII art is defined as (by me) an ASCII art with only one kind of non-white-spaces character (in our case: an asteriks *). And as output produce a standard ASCII art (all ASCII characters are accepted) which should remember the contourn of the first.

The purpose of using more than one character in the output is to make some edges ssmoother. For instance, one could let this input


could became:

    _/   ) 
  _/    /
 /      |
|      /
|      \
 \      |
  `\     |

The input \n separated string as input. Each line has a maximum of 80 characters. The number of rows is not specified.

I'd put it as a popularity-contest since, beside my simple code, I'd like to see more "round" edge detections which use more than one character in smooth edges.

Also, I don't want to tag it as code-golf since I'm quite sure one can do this job using aplay (with ASCII art renderer) and command line GIMP (to apply edge detection).

As a popularity contest, there are no strict rules on how the output should be..just use your fantasy!

This is my sample program:

import fileinput as f
import re as r
import copy as c
a,s,p='*',' ','+'
def read(n):
    s=[list(' '*n)]
    for l in f.input():
        k=list(r.sub('[^ ^\%c]'%a,'',' '+l+' '))
        s.append(k+[' ']*(n-len(k)))
    s.append([' ']*n)
    return s
def np(s):
    for l in s[1:-1]:
        for w in l[1:-1]: print(w,end='')
def grow(i):
    for x in range(1,len(o)-1):
        for y in range(1,len(o[x])-1):
            if(i[x][y]==a): o[x-1][y-1]=o[x-1][y+1]=o[x-1][y]=o[x+1][y]=o[x+1][y-1]=o[x+1][y+1]=o[x][y+1]=o[x][y-1]=a

    return o
def diff(i,o):
    for x in range(0,len(i)):
        for y in range(0,len(i[x])):
            if(i[x][y]==a and o[x][y]==s): l.append(p)
            else: l.append(s)
    return c

Here below I put both input of the programs. It is an 80x70 ASCII ART. It means it has 70 lines of 80 characters, each separated by \n.

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

A possible output could be:

                                         +++++             ++++
                                    ++++++     ++++++++++     +++
                                   ++      +++++        +++++   +++++
                            ++++++++   +++++                ++++    ++
                         ++++         ++                       ++++  ++
                    ++++++           ++                           ++  ++
                +++++      +++       +   +++++                     ++  ++
             ++++     +++++++       ++  ++   ++                     ++  ++
            ++    +++++   ++        +   +     +                  +++++++ ++
          +++  ++++      ++         +  ++     ++                ++     ++ ++
         ++   ++        ++         ++  +       +                +      ++  ++
        ++  +++         +          +  ++       +               ++      +++  +
       ++  ++          ++          + ++       ++               +        +++ +
      ++ +++          ++           + +      +++                +        + + ++
      +  +            +            + +     ++                  +        ++++ +
     ++ ++           ++            + ++   ++                   ++        + + +
    ++ ++            +             +  +++++                     ++      ++ + +
   ++ ++             +             +                             +++   ++  + +
   +  +             ++             +                               +++++   + +
  ++ ++             +              +                                      ++ +
  +  +              +             ++                                      +  +
 ++ ++             ++             +                                       +  ++
++  +              +             ++                                       +   ++
+   +              +             +                                        +    +
+  ++             ++            ++                                        +    +
+  +              +             +         +++++++                         +    +
+  +              +             +        ++     ++        ++++            +    +
+  +              +             +        +  +++  +       ++  +++          +    +
+  +              ++            +        + ++ ++ +      ++  +  ++         +    +
+ ++               +            ++      ++  +++  +      +  +++  ++        +    +
+ +                +             +      +       ++      +  +++   +        +    +
+ +                +            ++      ++     ++       ++       +        +    +
+ +   +++          ++            ++      +   +++         +++     +       ++    +
  +  ++ ++          +             ++     +++++             +    ++      ++     +
  + ++   ++         +              +                       ++++++      ++     ++
 ++++     +         ++             +++                                ++      +
  +       +          ++              ++            +++              +++       +
          +           +               ++++        ++ ++           +++         +
          ++          ++                 ++++     +   +        ++++           +
           +           ++                   +++++ +++++    +++++              +
           ++           ++                      +++   ++++++                  +
            ++           +                 +++++  +++++                       +
             ++          +                  +  +++    +++++                   +
              +++        +                  ++   ++++++  +                    +
                +        ++                  +           ++                   +
               ++        +                   +            +                   +
                +++      ++                  +           ++                  ++
                  ++      +                  +           +                   +
                   +++    ++                 +         +++                   +
                     ++++++                  +        ++                    ++
                                             ++     +++                     +
                                              +    ++                       +
                        +++++                 ++++++                        +
+                      ++   ++                   +                          +
+                     ++     +                                             ++
+                     +      +                            ++               +
+                    ++      +                          ++++               +
+                    +       +                     ++++++ ++               +
+                   ++       +                    ++      +                +
+                  ++        +                 ++++       +                +
+                 ++         ++                +          +               ++
+                 +           +                ++         +               +
+                 +           +                 +         +               +
++                +           +                 ++        +               +
 ++              ++           +                  +        +               ++
  ++++++++++++++++            +++                +        +                +
                                ++              ++        ++               +
                                 ++++++++++++++++          ++              +
                                                            ++            ++

This is also the output produced by the script above. Of course it is not the best output and I'm sure one can easily produce a smoother one.

  • 1
    \$\begingroup\$ It would be useful to be more precise about which characters should be non-blank in the output: characters which were non-blank in the input but adjacent to blanks, or characters which were blank in the input but adjacent to non-blanks? \$\endgroup\$ Commented Apr 4, 2014 at 9:50
  • \$\begingroup\$ Thanks for pointing. I re-written the phrase in the answer. You can use every ASCII character in the output (as usual ASCII art). E.g. I used only + symbol, but one could makes round edges using symbols like \ or / etc.. \$\endgroup\$ Commented Apr 4, 2014 at 9:55
  • \$\begingroup\$ edited again... \$\endgroup\$ Commented Apr 4, 2014 at 10:09
  • \$\begingroup\$ Can you define the input that will be used by all the participants? It's necessary to have only one input to compare the outputs of the different answers. The first example is too simple and the last one is too long. So I suggest to use something between these 2 examples. \$\endgroup\$ Commented Apr 4, 2014 at 17:29
  • \$\begingroup\$ Thanks, I chosen a cute panda as input. \$\endgroup\$ Commented Apr 6, 2014 at 8:09
  • 1
    \$\begingroup\$ one could let this input (…) could became → try something like "this input (…) could become" outpuit → output \$\endgroup\$ Commented Apr 7, 2014 at 13:31
  • \$\begingroup\$ I edited it now, so do you people thinks it is a good question? \$\endgroup\$ Commented Apr 9, 2014 at 17:15
  • \$\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\$
    – user58826
    Commented Jun 9, 2017 at 16:32
  • \$\begingroup\$ Hi @programmer5000 , I already asked such a question. Do you mean to re-use it again? See: codegolf.stackexchange.com/questions/26139/… \$\endgroup\$ Commented Jun 12, 2017 at 13:39

Find sociable numbers


A number is perfect if it is the sum of its divisors; for instance 6=1+2+3

A pair of numbers is friendly if they are the sum of each other's divisors; for instance 284=1+2+4+5+10+11+20+22+44+55+110 and 220=1+2+4+71+142.

In general, a list of n numbers is sociable if each element is the sum of divisors of the previous elements, with the first being the sum of divisors of the last.


An integer, n on STDIN.


A list of n numbers which are sociable, in the order outlined above, each on its own line. If you can't find any suitable list, you may output nothing, False, or 0, but you must search up to at least 2^32-1, and preferably as high as your language will allow


This is code-golf, so the shortest code wins. However, I will also create a bounty to be awarded to the fastest program, as measured on my command-line (Windows 7 with GNU coreutils, python27, python3, node.js, perl) or in a web IDE in chrome (brainfuck, golfscript?)

Edit: to clarify the relationship between input and output

  • \$\begingroup\$ The relation between the input and output is unclear. Are we asked to find the loop of sociable numbers that the input number leads to by iterating "sum of proper divisors"? \$\endgroup\$ Commented Apr 19, 2014 at 11:17
  • 1
    \$\begingroup\$ @JanDvorak, no, we're asked to find a cycle of length n in the directed graph whose vertices are the natural numbers and whose edges are i -> aliquot_sum(i). \$\endgroup\$ Commented Apr 19, 2014 at 19:09
  • 4
    \$\begingroup\$ I don't think it's a good idea to have a code golf and a fastest code challenge in the same problem. You'll get incomparable answers. Maybe make a composite score that incorporates time and length? \$\endgroup\$
    – isaacg
    Commented Apr 21, 2014 at 0:58
  • \$\begingroup\$ That may be better. \$\endgroup\$
    – Claudia
    Commented Apr 21, 2014 at 21:08
  • \$\begingroup\$ Would you allow the usage of predefined functions that calculate the aliquot sum? \$\endgroup\$
    – Wrzlprmft
    Commented Apr 22, 2014 at 13:49
  • \$\begingroup\$ @alexander-brett Are you going to post this? \$\endgroup\$
    – Oliver Ni
    Commented Oct 9, 2016 at 4:28
  • \$\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\$
    – user58826
    Commented Jun 9, 2017 at 16:38

Save your job in QA!

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

"But why?" You ask

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

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

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

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

The challenge

Your challenge is to write the following:

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

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


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

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

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

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

Cube puzzle

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

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


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


enter image description here

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

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


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

Winning criterion:

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

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

Paired Programming: Down Periscope!

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

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

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

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

Sensors down, Captain

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

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

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

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

Take us down

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

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

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

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

Fire torpedoes!

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

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

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

The Arena

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

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

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

Realistic Stock Market

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

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

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

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

Buying and Selling

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

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

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

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

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

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

The Tournament Setup

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

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

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

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

A Single Turn

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

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

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

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

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

Recording the past

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


Input will consist of 3 arguments in this order:

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

The data for the stocks will be formatted like this:

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

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

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

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


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

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

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


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

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

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

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

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

Brainfuck compression

Possible Duplicate

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


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

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

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

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


Could this challenge include decompression as well?

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

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

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

Comment Java Code

Little Billy is in an AP computer science class and his teacher requires him to comment his code (in Java) even though Little Billy thinks it is redundant. Little Billy is a lazy person and so he wants a program to comment for him.

The Challenge:

Make a program in any language that gets a text file as input and saves the commented version to a new text file (or to STDOUT) changing it in the following ways:

  • Add comments before all contructors:

* Constructs a new instance of (class whatever).
* if applicable: @param nameOfVariable is the name of variable

  • Add comments before any functions:

* if applicable: @param nameOfVariable is the name of variable.
* if applicable: @return nameOfReturnVariable is the name of return variable.

  • Add a comment before static void main(String[] args) if present:

* This is where the program starts.
* @param args is the command line arguments passed to the program.

  • Add comments before the class declaration (not applicable for inner classes)

* class NameOfClass is another great example of Object Oriented Programming!

For example, given this:

public class Car {
    private double gas;
    private double mpg;

    public static void main(String[] args) {
        new Car(20,20);

    public Car(){}

    public Car(double gasInVehicle, double milesPerGallon){
        gas = gasInVehicle;
        mpg = milesPerGallon;

    public void drive(double milesToDrive){

    public double getGas(){
        double gasolineInTank = gas;
        return gasolineInTank;


Your program should output this:

 * class Car is another great example of Object Oriented Programming!
public class Car {
    private double gas;
    private double mpg;
     * @param args is the command line arguments passed to the program.
    public static void main(String[] args) {
        new Car(20,20);
     * Constructs a new instance of Car.
    public Car(){}
     * Constucts a new instance of Car.
     * @param gasInVehicle is the gas in vehicle.
     * @param milesPerGallon is the miles per gallon.
    public Car(double gasInVehicle, double milesPerGallon){
        gas = gasInVehicle;
        mpg = milesPerGallon;
     * @param milesToDrive is the miles to drive
    public void drive(double milesToDrive){
     * @return gasolineInTank is the gasoline in tank.
    public double getGas(){
        double gasolineInTank = gas;
        return gasolineInTank;

Extended Info

  • Because Little Billy's class is only on week 3, Little Billy's knowledge of complex Java statements is pretty limited. In other words, only common functions, class declarations, constructors and instance variables will be included; objects/variables/resources are limited to Java primitives and their wrapper classes and Math.
  • Each variable name is separated for its definition according to standard camel case rules, with an exception of the first letter, which may be capitalized. For example,

milesToRun = miles to run.
milestoRun = milesto run.
MilesToRun = miles to run.
parseXML = parse xml - each successive capital letter (with a minimum of 3 in a row) is considered an acronym, so GetABuffer would become get a buffer. parseXM is parse x m.

If it is a parameter -

@param milesToRun is the miles to run.

  • Your program should be able to handle multiple arguments to functions
  • There should be no lines with only " * ".
  • Assume all variables and parameters are formatted correctly (e.g. all camel case, only letters, etc.)
  • Indentation is not critical. However, all newlines should remain.
  • You may also assume that statements ending in a semicolon are 1 line each


This is code-golf, so shortest code wins (in bytes).

  • 1
    \$\begingroup\$ when you say "assume all camel case"... what about the unlikely method name GetABuffer? If that is valid and should produce "get a buffer", then what about ParseXML? \$\endgroup\$ Commented Sep 11, 2014 at 10:12
  • 1
    \$\begingroup\$ Similar to codegolf.stackexchange.com/q/3241/194 . The thing that would potentially make this more difficult is parsing Java, but then you need to provide some details on the grammar. I also notice that your spec and examples avoid all of the tricky stuff around generics. \$\endgroup\$ Commented Sep 11, 2014 at 11:32
  • \$\begingroup\$ I think it should be parseXml. \$\endgroup\$ Commented Sep 13, 2014 at 15:07

Coloring Book

Given a black-and-white raster line drawing (no anti-aliasing, with fully enclosed regions), write a program that will color it in. Something maybe like below, though I'd clean up messy JPGs into clean B&W PNGs to start with:


Could either be a , to give freedom in create more interesting output (gradients, patterns, how to select "better" colors, other images). Along the lines of patterns and gradients, I'd opt for simpler stock "prompts", preferably animals, to show off solutions:


...or perhaps if each region has a specified color given by a swatch inside it: so the program would basically need to find-the-color then flood-fill. Sounds boring, I prefer more creativity.

  • \$\begingroup\$ The flood fill would indeed be quite trivial, but as a popularity contest this could become too much of an art contest and less of a programming contest. \$\endgroup\$ Commented Oct 10, 2014 at 9:45
  • \$\begingroup\$ In my mind's eye I kinda pictured an elementary school classroom wall with the same line drawing jazzed up every which way. \$\endgroup\$
    – Nick T
    Commented Oct 10, 2014 at 10:18
  • \$\begingroup\$ I do think there is reasonable technical skill involved in creating something to dynamically create said art. Gradients, patterns, masking other images into regions, coloring outside the lines, and something even more interesting than what I can come up with all seem to take reasonable skill. Especially for a few arbitrary input drawings. \$\endgroup\$
    – Nick T
    Commented Oct 10, 2014 at 10:26
  • 2
    \$\begingroup\$ If you can come up with a testable criterion, you might be able to get an interesting code-golf which asks for cel shading rather than just floodfill. \$\endgroup\$ Commented Oct 10, 2014 at 10:42
  • \$\begingroup\$ You could specify a rule for which colour should be used. For example, you could colour based on area or perimeter of the region being filled (or some combination of both). This would colour similar regions in similar colours and give the impression of being chosen for the image, but would still be rigorously defined enough to make it a code golf. \$\endgroup\$ Commented Aug 26, 2015 at 14:50
  • \$\begingroup\$ @programmer5000 feel free to take this one. Are you thinking about doing code-golf somehow or a popularity contest? \$\endgroup\$
    – Nick T
    Commented Jun 9, 2017 at 23:09

Score a Mahjong Hand

So you've built a solver for which tiles you need to complete a Mahjong hand, but you've heard that certain hands are worth more than others and sometimes a hand that scores too low can't even win.

So, you decide to build a program that will score hands for you.

This time, however, you will be making it for the full mahjong set. There are a total of 136 tiles in this variant, four copies of each of the following:

  • 1 coin to 9 coins, represented from 1p to 9p.
  • 1 stalk to 9 stalks, represented from 1s to 9s.
  • 1 myriad to 9 myriads, represented from 1m to 9m.
  • four winds, represented as EE, SS, WW, and NN.
  • three dragon tiles, represented as ZZ, FF, and BB.

The winds and dragons are known as honour tiles, and they are not part of any suit.

A standard mahjong hand consists of four sets and a pair. A set can be any of:

  • A chow, which is a sequence of three tiles in the same suit. Winds and dragon tiles cannot be part of a chow.
  • A pong, which is a group of three of the same tile.
  • A kong, which is a group of four of the same tile. Every kong increases the total number of tiles in a player's hand by 1.

Every chow and pong has three tiles in it, while a kong has four. So a winning hand can have anywhere from 14 to 18 tiles, depending on the number of kongs.

Now, the score that a hand has is based on fan. A valid winning hand has no fan by default. However, the following patterns count for fan:


  • A pong or kong of dragons (e.g. ZZ ZZ ZZ): 1 fan
  • A pong or kong of winds (e.g. EE EE EE or SS SS SS SS): 1 fan


  • A straight, 1-9 in a suit as three sets (e.g. 1s 2s 3s 4s 5s 6s 7s 8s 9s + 1 more set and a pair): 3 fan
  • A broken straight, 1-9 in a suit plus an additional 3, 5, and 7 (1s 2s 3s 3s 4s 5s 5s 6s 7s 7s 8s 9s): 5 fan
  • A pong or kong of all three dragons (e.g. ZZ ZZ ZZ FF FF FF BB BB BB BB): 7 fan
  • Four winds (EE EE EE SS SS SS WW WW WW NN NN NN + a pair): 10 fan
  • Nine Gates (1 1 1 2 3 4 5 6 7 8 9 9 9 of any single suit, plus one more of any tile in the suit): 14 fan (effectively 20 fan because of one-suit)

Entire hand patterns

  • Entire hand is chows (e.g. 1s 2s 3s 6s 7s 8s 2p 3p 4p 7m 8m 9m NN NN): 1 fan
  • Entire hand is pongs or kongs (but not all kongs) (e.g. 1m 1m 1m 3s 3s 3s 7p 7p 7p NN NN NN EE EE): 3 fan
  • Entire hand is kongs only (e.g. 1m 1m 1m 1m 3s 3s 3s 3s 7p 7p 7p 7p NN NN NN NN EE EE): 10 fan
  • All tiles from one suit + honours (e.g 1p 1p 1p 4p 4p 4p 7p 8p 9p SS SS SS EE EE): 3 fan
  • All tiles from one suit (e.g. 1p 1p 1p 4p 4p 4p 7p 8p 9p 6p 6p 6p 5p 5p): 6 fan
  • All tiles honours (e.g NN NN NN ZZ ZZ ZZ BB BB BB SS SS SS EE EE): 9 fan

Special hands

The hands below are scored specially and do not follow the four-sets-and-a-pair rule.

  • Seven Pairs (seven pairs of any tiles): 2 fan
  • Seven pairs in the same suit: 10 fan
  • Seven honour pairs: 20 fan
  • Thirteen Orphans (1p 9p 1s 9s 1m 9m EE SS WW NN ZZ FF BB and one more of any of these 13): 10 fan

Note that you only have to account for the value of the hand itself - you don't need to care about what the prevailing wind is or whether the tile was self-drawn, by discard, or anything else.

Also note that a hand may fulfill multiple criteria. If it does, add up all the fan from each criterion it fulfills, except if the hand is a special hand.

  • \$\begingroup\$ I won't be around for long. But sure, if you can make a chatroom and link to it here, I'll check in on it periodically. \$\endgroup\$
    – Joe Z.
    Commented Dec 19, 2014 at 3:40
  • \$\begingroup\$ Chat link: here \$\endgroup\$
    – Sp3000
    Commented Dec 19, 2014 at 3:47
  • \$\begingroup\$ Oh, just using that one? It might get muddled up in the rest of the messages, though. \$\endgroup\$
    – Joe Z.
    Commented Dec 19, 2014 at 5:25
  • \$\begingroup\$ Some ambiguous case that never happens in a real game: 111122233345555, which can be either 1111 222 33 345 555 or 11 123 123 234 5555. Both are 6 fan, though. Btw: psm are Japanese and ZFB are Chinese. Shouldn't that be at least consistent? (Or is that the standard somewhere?) \$\endgroup\$
    – jimmy23013
    Commented Dec 19, 2014 at 11:01
  • \$\begingroup\$ @user23013 In my question I was using Japanese, just so I could plug tests into Tenhou's solver. They use 1z2z3z... for honours. ZFB is indeed Chinese, but unfortunately taking the initials for Japanese gives CHH. I'm not sure if there's a standard anywhere. \$\endgroup\$
    – Sp3000
    Commented Dec 19, 2014 at 14:21
  • \$\begingroup\$ @Sp3000 In fact it would be HHC in the Japanese order... I think most Japanese people don't use letters for honors. And Chinese people don't use letters at all. I did some search and found some English-speaking people are just using something worse: Red, Green, ... \$\endgroup\$
    – jimmy23013
    Commented Dec 19, 2014 at 15:48
  • \$\begingroup\$ ZFB is Chinese, and psm was Japanese/Cantonese but there I was just following the convention from the previous question. I can change it to BSW if you want, though. \$\endgroup\$
    – Joe Z.
    Commented Dec 19, 2014 at 20:30
  • \$\begingroup\$ I was just nitpicking... never mind. \$\endgroup\$
    – jimmy23013
    Commented Dec 20, 2014 at 9:56
  • \$\begingroup\$ The multiple maching criteria should be clarified: For example seven pairs in the same suit, scores just 10 total - not 12. In otherwords, it isn't considered to match both "Seven Pairs" and "Seven Pairs in the same suit". \$\endgroup\$ Commented Jan 2, 2015 at 15:42

Invert the matrix

The name says it all. I am surprised that there is no preexisting question on calculating matrix inversion

Given an nXn invertible matrix, your task is to output its inverse.


  • Floating point precision of at least 3 significant decimal places is required
  • You can assume that the input matrix will always have an inverse
  • You cannot use any inbuilt methods (or external libraries) to perform any of the following tasks:
    • Calculate the inverse
    • Solve system of equations
    • Calculate determinant
    • Multiply two matrices or calculate dot product.
  • In other words, your code has to calculate the inverse using any of the mathematical methods itself. (If I missed out any inbuilt methods in the above rule, this rule should make it clear that it cannot be used)
  • You cannot calculate inverse by randomly generate random matrix and then multiply with the input to check for unit matrix.


Input can be in a format of your choice. For example:

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


1 3 4
5 7 8
3 4 5



The output should be in the same format as the input, except for 1 requirement that each row of the matrix should be in a separate line with elements of the same row on the same line.

This is code-golf so shortest code in bytes win.

Sandbox notes

What do you think of the problem ? Too mundane ? Too trivial ? Need any extra rule to make it more interesting ?

  • \$\begingroup\$ There is a pre-existing question, although it only covers 2x2. \$\endgroup\$ Commented Jan 3, 2015 at 8:28
  • \$\begingroup\$ @PeterTaylor Yeah, also, it is based on system of equations, which is related but not exactly same as Inverse (Inverse is a part of solving equations). So size plus this fact should make this question different enough ? \$\endgroup\$
    – Optimizer
    Commented Jan 3, 2015 at 8:32
  • \$\begingroup\$ "Floating point precision upto 3 decimal places is required" - did you mean "Floating point precision of at least 3 decimal places is required"? \$\endgroup\$ Commented Jan 3, 2015 at 10:11
  • \$\begingroup\$ @JanDvorak err. \$\endgroup\$
    – Optimizer
    Commented Jan 3, 2015 at 10:13
  • 4
    \$\begingroup\$ The whole business of numerical accuracy is a minefield for this because there are many ill-conditioned instances. You can't talk in terms of decimal places unless you either require people to work in arbitrary precision or guarantee some very conservative bounds on the input and output values. (Unless you want to merely go for conservative bounds and include some test cases which will disqualify naïve Gaussian elimination and force people to do a Bareiss-style approach, but that will lead to having not more than one or two correct answers and probably a dozen incorrect ones). \$\endgroup\$ Commented Jan 3, 2015 at 16:34
  • \$\begingroup\$ To get around thorny questions of ill-conditioned matrices and the possibility of divide-by-zero, how about only requiring that the algorithm work with high probability on random Gaussian matrices of size at most 100? \$\endgroup\$
    – xnor
    Commented Jan 3, 2015 at 18:00
  • \$\begingroup\$ @PeterTaylor I might not have understood even 10% of that comment. Can you please tell me what can I put in place of that rule then ? \$\endgroup\$
    – Optimizer
    Commented Jan 3, 2015 at 19:14
  • \$\begingroup\$ @xnor what do you mean by ill-conditioned matrices ? \$\endgroup\$
    – Optimizer
    Commented Jan 3, 2015 at 19:15
  • \$\begingroup\$ No, I can't. I don't consider myself qualified to write a spec for inverting matrices. I know what the problem is, but I don't understand it well enough to formulate validity constraints. I think it would be best to leave the idea for someone who has a firm grasp of the numerical analysis of linear algebra to pick up and finish. \$\endgroup\$ Commented Jan 3, 2015 at 19:41
  • \$\begingroup\$ @PeterTaylor I disagree with you. The purpose of this challenge is not to get an mathematically perfect matrix inversion code, but instead, a code that calculates the inverse in the shortest and smartest way. Martin suggested in chat that the floating point precision upto certain significant digits can be made a compulsion till a matrix size of say 10. Simply hoping to get a mathematically experienced person who has mastery in matrix inversion to pick up the challenge is a very pessimistic approach. \$\endgroup\$
    – Optimizer
    Commented Jan 3, 2015 at 20:38
  • \$\begingroup\$ @Optimizer Here's the issue: say I write a row reduction algorithm. I want to subtract a multiple of the first row from the second in order to zero out the first entry of the second row. Do I have to consider the case where the first entry of the first row is zero, so I get a divide-by-zero error? Ok, say I have a separate check if equals 0. What if that entry is supposed to be 0, but as a result of a previous calculation is 0.00000001, failing the check? Now my second row is ginormous and it shouldn't be. \$\endgroup\$
    – xnor
    Commented Jan 4, 2015 at 2:47
  • \$\begingroup\$ @Optimizer Alternatively, finding the inverse mod 2 would avoid accuracy issues. \$\endgroup\$
    – xnor
    Commented Jan 7, 2015 at 4:21
  • \$\begingroup\$ @xnor mod 2 as in ? \$\endgroup\$
    – Optimizer
    Commented Jan 7, 2015 at 4:27

Responsible governance


For years, the Federal government of the United States has been in chaos. The Presidency and Congress are under different parties, and there are no compromises in sight. Instead of passing a budget or improving the tax code, the politicians are squabbling as the country teeters on the brink of economic collapse. It seems that a few more years of political dysfunction will soon reduce the United States to rubble.

Yet, some have noticed that many state governments seem to be functioning. Taxes are being reformed, education is being improved, and even compromise can be found on occasion!

The solution is clear. The federal government must be dissolved. Each state will control its own eduction, infrastructure, and healthcare, but the budgets will be pooled. As the governor of your state, you must use the country's funds to improve your constituents' lives, but also be frugal enough to let your neighbors prosper as well.


This system of government will be in place for 10 years (120 months), after which the results of this experiment will be analyzed. Each month, every governor will be given the opportunity to use the country's funds to pay for one project of their choice.

The government starts with $1,000,000 in the bank, times the number of states. In every state, life expectancy is 75 years, education is at 95 IQ, and the infrastructure gets a rating of 65 points.

Every year, the following happens:

  • First, taxes are collected and centralized expenses are paid.
  • For each of the next twelve months:
    • Each governor, in order, is allowed to finance a project.
  • Finally, information about each states' education, healthcare, and infrastructure is updated to reflect the projects built.


The final score is the government's total funds, times average state's life expectancy, times the average state's IQ, times the average state's infrastructure rating. (These averages are not weighted by population.)

This entire experiment will be performed many times. Each time, a different governor will be excluded. The winner will be the governor such that the final score is the worst when they are excluded, since they must have had the biggest impact on the government's success.


  • N is the number of governors (not counting the excluded one)
  • L is the life expectancy of a particular state.
  • La is the average life expectancy.
  • E is the IQ of a particular state.
  • Ea is the average IQ.
  • T is the infrastructure rating of a particular state.
  • Ta is the average infrastructure rating.

    Revenues and expenses

  • Annual revenue: $ N Ea2 Ta

  • Annual expenses: $10,000,000,000,000 N / La3 / Ta


  • Each of the three factors (health, education, and infrastructure) is calculated on a state-by-state basis. L starts at 75, E starts at 95, and T starts at 65.

  • For each factor, the bonuses are cumulative.
  • For example, the bonuses L +2, L +5 mean that L = ( 75 + 2 + 5 ) = 82.
  • Each project can be done only once by each state.
  • Each project has an associated six-letter code (for I/O).

    List of projects

  • [ENOUGH] Enough medicine: L +5, cost: $300,000

  • [CANSCR] Early cancer screenings: L + 4, cost $200,000
  • [FREECC] Free community college: E +10, cost: $400,000
  • [LIBRAR] Library system: E + 3, cost: $150,000
  • [MUSEUM] Museums E + 1 in each state, cost: $500,000

many more in the actual challenge...

Your program

Write a function in Java, Python 2, or Ruby, which accepts an integer (the government's funds) and returns an optional six-letter code, corresponding to the project chosen. If nothing is returned, or the returned value is invalid, or the chosen project was already built by you, or costs more than the government's funds, no project will be built for this month.

You may not use any I/O, except for one file called "<program-name>.txt, which you may use however you wish, provided it's kept under 2 megabytes at all times.

Some questions:

  1. Are the rules completely clear?
  2. Are there any perverse incentives? The goal should be to improve one's own state while being frugal with the government's funds.
  3. In the first section too political?
  4. Is the challenge too complicated?
  • \$\begingroup\$ I wonder about the formulas used for score/revenue/expenses. Have you run this a few times with dummy states to see if it works in practice? I'd hate to see a simple, constant choice resulting in a clear winner with no good way to stop it. \$\endgroup\$
    – Geobits
    Commented Jan 26, 2015 at 2:23
  • \$\begingroup\$ That's a good point; thanks for the feedback. The existing formulas are sort of placeholders for now. Once the other details are worked out, then I'll focus on getting the formulas balanced. \$\endgroup\$
    – Ypnypn
    Commented Jan 26, 2015 at 2:48

Real-Time Hovercraft Battle

Hovercrafts are cool. Hovercrafts with rail guns are even cooler. In this challenge, you will write a program to controller a battling hovercraft.

The hovercrafts in this game obey the laws of physics. A hovercraft with no acceleration will continue moving in a straight line. Also, a spinning hovercraft will continue to spin.

At each moment in time, the hovercraft's motion is defined by a few variables: the location, angle, linear velocity, and angular velocity of the hovercraft.

Hovercrafts are circles of radius 4, with a clear "front" and "back" end. On the left and right there are two forward-facing fans which serve as propulsion. Each fan has 8 power settings, from -3 to +4. These fans control additional aspects of the hovercraft's motion, the linear and angular acceleration.

Todo: determine the mass and moment of inertia for the hovercraft, which will then allow me to determine which power settings have which effects.

The real fun begins with the rail gun. The rail gun fires from the front of the hovercraft and deals damage when it strikes the side of the opposing hovercraft. The ammunition travels at a fast speed but finite, and the angle of the shot depends on the motion of the hovercraft. Firing the railgun also produces a recoil effect.

Note: I need to prevent the "rotating turret" strategy: spin really fast and fire when you find yourself pointed at something. An a truly instantaneous shot would never miss in this circumstance.

In order to power the rail gun, you must first charge a capacitor. Capacitor charging can be turned on and off. When the capacitor is charging, the fans will have reduced thrust. Once the capacitor stops charging (either it is full or charging is turned off) the thrusters will act normally again. You can still fire the rail gun when the capacitor is charging: the shot will have reduced damage. By default, the capacitor starts empty with charging on.

The Tournament

All of the participants will participate in a series of 1v1v1v1 battles. The goal is to survive the longest.

The battle arena is a radius 400 circle. Hovercraft can collide with the boundary, bounce,and take a little damage. At the start of the match, one hovercraft will be randomly located (1 per quadrant).

The finish order for a round will be determined by the order of death. After a certain period of time, all remaining hovercrafts will be deemed co-champions of that round.

After a decent number of battles (a number not currently determined, but something less than an exhaustive search but enough to determine the overall winner with non-negative confidence), the finish orders for each battle will be treated as ballots in a form of ranked voting scheme. By using a mathematically sound voting scheme, the final order should represent the results of the battles pretty well.

I have not started the controller yet.

This will be a real-time game. Each hovercraft program can request updates and send commands in real-time. This means that game ticks can happen while your program is running, and each game tick is a very small increment of time (as fast as feasible).

  • \$\begingroup\$ Check out Robocode. It is a long-running contest with comparable rules. What vision do the players have? Can you see the orientation of other participants? \$\endgroup\$
    – Franky
    Commented Feb 15, 2015 at 10:49

Best Approximating Polynomial


Let f(x) and g(x) be two continuous real-valued functions over the interval [a, b], where a < b.  The mean squared error (or simply "error" hereafter) between f(x) and g(x) is defined as

Equation 1

Roughly speaking, the smaller the error is, the closer f(x) and g(x) are.

In this challenge, f(x) will be some user-supplied target function and g(x) will be a polynomial of some maximal degree n.  The goal is to find the polynomial g(x) that minimizes the error w.r.t. f(x) (such a polynomial exists and is unique;) we say that g(x) is the best approximation of f(x) over the interval [a, b] using a polynomial of degree at most n.

For example, let's take the function f(x) = cos x over the interval [0, ½π] (which contains all the "interesting" information about this function), and look for a polynomial of degree at most 2. As you might know, the Taylor expansion of cos x up to degree 2 is t(x) = 1 - ½x2.  The error between t(x) and f(x) is approximately 6.25×10-3.  We can do better than that! If I got my math right, the best approximation of cos x over the interval [0, ½π] using a polynomial of degree at most 2 is (brace yourselves):

Equation 2

or approximately g(x) ≈ -0.34 x2 - 0.13 x + 1.02.  The error between g(x) and f(x) is approximately 7.03×10-5—two orders of magnitude better! The difference is very notable, as the following plot shows:

Plot 1


Write a program or a function that takes a function f(x), an interval [a, b], where a < b, and a nonnegative integer n, and returns the polynomial of degree at most n that best approximates f(x) over the given interval.


You may read the input through STDIN, the command line, as function arguments or an equivalent method. Note that you don't have to accept a, b and n in any specific format; particularly, you don't have to read a and b as [a, b].

You should accept the function f(x) in one of the following forms:

  • As a language-level function, function-like object, polymorphic object or any other equivalent method your language uses to communicate functions.
  • As a string containing an expression. The actual format of the string is flexible, but it should be expressive enough to allow basic arithmetic operations, exponentiation, and preferably also logarithms and basic trigonometric functions. The intention is for it to be used with something like eval. Note that you're allowed to require the string to be formatted in some convenient way (within reason), for example, pre-wrapped in a function
    (as in "function (x) { return x + Math.sin(x); }").
  • If, and only if, both of the above methods are impractical in your language, you may not take the function as input and assume that the function is already defined by the user. In this case, add to your score a +16byte penalty.

You may assume that the input is valid.

Please specify how your program accepts its input in your post.


You may write the output to STDOUT, return it as the function's result or use an equivalent method. You may express the polynomial as a list of coefficients (e.g., [1, -2, 1]), using some pretty-printed form (e.g., x^2 - 2x + 1) or some other equivalent method. Either way, it should be easy to determine the coefficients of the different terms from your output; so, for example, you may not return the polynomial as an opaque function.

Note that unlike the example given at the beginning of the post, you don't have to produce symbolic output (unless you want to); a numeric output is fine.

Please specify how your program returns its output in your post. If the order of the coefficients may be ambiguous, make sure to clarify it.

Accuracy and Run Time

The numerical accuracy of your program is most likely going to be dependent on the target function, the degree of the polynomial and the amount of time you allow it to run. As a result, giving a general accuracy requirement is impractical. However, your program should process each of the below test cases in less than a minute and produce a polynomial whose error w.r.t. the target function is no worse than the error specified in the test case.

Additional Rules

  • You may not use any function that performs this specific task.


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

Test Cases

Recall that your program should complete each of the following test cases in less than a minute, with an error that is less than or equal to the specified error. That being said, this is not a hard and fast rule; if your program struggles with a couple of test cases, that's fine. Note that the approximating polynomials listed in the test cases are just an approximation and are only given for illustration. Although theoretically each case has a unique optimal polynomial, your program might produce a notably different one; this is especially true for the higher degree polynomials. However, both polynomials should behave similarly over the given interval, which is why the correctness of your program is determined by the error. Likewise, the errors listed in the test cases are only an approximation and are not necessarily the errors of the corresponding listed polynomials—they're just a lower-bound for accuracy.

Test 1
f(x) = sin(x)
From: -pi
To: pi
Max. Deg.: 0
g(x) = 0
e^2 = 5.0001 * 10^-1

Test 2
f(x) = sin(x)
From: -pi
To: pi
Max. Deg.: 1
g(x) = 0.304 x
e^2 = 1.9604 * 10^-1

Test 3
f(x) = cos(x)
From: -pi
To: pi
Max. Deg.: 2
g(x) = -0.231 x^2 + 0.76
e^2 = 3.8032 * 10^-2

Test 4
f(x) = sin(x)
From: -pi
To: pi
Max. Deg.: 5
g(x) = 0.005643 x^5 - 0.155 x^3 + 0.988 x
e^2 = 1.8490 * 10^-5

Test 5
f(x) = cos(x)
From: 0
To: 3pi
Max. Deg.: 8
g(x) = 6.69465*10^-9 x^8 - 1.01005*10^-4 x^7 + 0.00332742 x^6 - 0.0400508 x^5 + 0.205029 x^4 - 0.351657 x^3 - 0.120773 x^2 - 0.169562 x + 1.01830
e^2 = 1.9764 * 10^-5

Test 6
f(x) = e^(-x^2)
From: -2
To: 2
Max. Deg.: 10
g(x) = -0.00143879 x^10 + 0.0211686 x^8 - 0.133468 x^6 + 0.473915 x^4 - 0.992265 x^2 + 0.999624
e^2 = 8.4405 * 10^-8

Test 7
f(x) = 1/(x^2 + 1)
From: -3
To: 3
Max. Deg.: 16
g(x) = 3.16504*10^-6 x^16 - 1.23974*10^-4 x^14 + 0.00203230 x^12 - 0.0181511 x^10 + 0.0966544 x^8 - 0.318123 x^6 + 0.662508 x^4 - 0.923653 x^2 + 0.996846
e^2 = 2.6 * 10^-6

Test 8
f(x) = e^((sin(x))^3)
From: 0
To: 2pi
Max. Deg.: 1
g(x) = -0.224 x + 1.87
e^2 = 2.6845 * 10^-1

Test 9
f(x) = (cos(x))^5
From: pi
To: 2pi
Max. Deg.: 17
g(x) = 6.31854*10^-12 x^17 - 1.63320*10^-11 x^16 - 2.78192*10^-10 x^15 - 8.73964*10^-10 x^14 - 2.74564*10^-9 x^13 + 5.59537*10^-8 x^12 - 2.70984*10^-8 x^11 - 2.61779*10^-5 x^10 - 2.67450*10^-7 x^9 - 8.40220*10^-7 x^8 + 0.3247516 x^7 - 7.3046333 x^6 + 72.908485 x^5 - 408.43197 x^4 + 1362.34294 x^3 - 2657.0269 x^2 + 2737.319113682029 x - 1100.1514
e^2 = 5.8 * 10^-5

Test 10
f(x) = sqrt(1 - x^2)
From: -1
To: 1
Max. Deg.: 20
g(x) = -627.601 x^20 + 2853.92 x^18 - 5499.47 x^16 + 5845.71 x^14 - 3738.80 x^12 + 1472.42 x^10 - 350.970 x^8 + 47.6426 x^6 - 3.39128 x^4 - 0.414096 x^2 + 0.999632
e^2 = 1.2 * 10^-6

Test 11
f(x) = sqrt(1 - x^2) + 0.1*sin(4*pi*x)
From: -1
To: 1
Max. Deg.: 18
g(x) = -203.563 x^18 + 141.013 x^17 + 821.952 x^16 - 757.063 x^15 - 1378.59 x^14 + 1771.07 x^13 + 1241.44 x^12 - 2345.58 x^11 - 648.127 x^10 + 1895.10 x^9 + 197.425 x^8 - 928.025 x^7 - 33.5970 x^6 + 254.982 x^5 + 2.70132 x^4 - 32.7510 x^3 - 0.590680 x^2 + 1.25167 x + 1.00047
e^2 = 1.9 * 10^-6

Test 12
f(x) = abs(x)
From: -1
To: 1
Max. Deg.: 6
g(x) = 1.46667 x^6 - 2.82024 x^4 + 2.30724 x^2 + 0.0854450
e^2 = 5.08635 * 10^-4

Test 13
f(x) = x*sin(x^1.2) + 10*sqrt(x)
From: 0
To: 2.5pi
Max. Deg.: 3
g(x) = -0.129 x^3 + 1.046 x^2 + 1.392 x + 6.98
e^2 = 7.3389 * 10^0

Test 14
f(x) = sin(log(1 + e^cos(x)))
From: 2
To: 10
Max. Deg.: 10
g(x) = 9.52190*10^-10 x^10 - 6.30342*10^-6 x^9 + 3.3746525*10^-4 x^8 - 0.0078575036 x^7 + 0.103708803 x^6 - 0.84926923 x^5 + 4.4421097 x^4 - 14.766225 x^3 + 30.153933 x^2 - 34.72483 x + 17.8389
e^2 = 5.4 * 10^-5

Test 15
f(x) = abs(log(x))
From: 1/e
To: e
Max. Deg.: 15
g(x) = 6.07034*10^-8 x^15 + 9.85444*10^-5 x^14 + 3.35349*10^-7 x^13 + 7.88206*10^-7 x^12 + 1.85260*10^-6 x^11 + 4.35436*10^-6 x^10 - 3.4245574 x^9 + 42.093925 x^8 - 228.714688 x^7 + 711.8547 x^6 - 1383.06 x^5 + 1720.8859 x^4 - 1357.596 x^3 + 651.1596 x^2 - 173.8175 x + 20.680
e^2 = 1.587 * 10^-4

Test Program

The following snippet can be used to compute the best approximating polynomial for a given function, as well as to calculate the error of your own approximations. Note that it has limited accuracy, and becomes numerically unstable for polynomials of degree over 20–30.

<style>#main {display: none;}#status_container {padding: 4px;}#status {padding: 5px;background-color: #fffdce;box-shadow: 1.5px 1.5px 3.5px #aaaaaa;font-size: 10pt;word-wrap: break-word;display: none;}#status[loading] {display: inline;}</style><span id="main"><table id="main_table"><tr><td><div id="plot_area"><div id="plot_float"><div id="plot_container"><div id="plot"></div></div></div></div></td><td><table class="field_table" id="field_table"><tr><td class="field_name">𝑓(𝑥)&nbsp;=</td><td><table class="padding_table"><tr><td><div class="input_container"><div class="input_underlay" id="expression0_underlay"></div><div class="input_error_underlay" id="expression0_error_underlay"></div><textarea class="input" id="expression0" spellcheck="false" oninput="update(0)">e^-(x/6) cos x</textarea></div></td></tr></table></td></tr><tr><td colspan="2"><table class="horz_field_table"><tr><td><table class="field_table"><tr><td class="field_name small_field_name">From</td><td><table><tr><td><div class="input_container"><div class="input_underlay" id="from_underlay"></div><div class="input_error_underlay" id="from_error_underlay"></div><textarea class="input" id="from" spellcheck="false" oninput="update()">0</textarea></div></td></tr></table></td></tr></table></td><td><table class="field_table"><tr><td class="field_name small_field_name">To</td><td><table><tr><td><div class="input_container"><div class="input_underlay" id="to_underlay"></div><div class="input_error_underlay" id="to_error_underlay"></div><textarea class="input" id="to" spellcheck="false" oninput="update()">2.5pi</textarea></div></td></tr></table></td></tr></table></td><td><table class="field_table"><tr><td class="field_name small_field_name">Max.&nbsp;Deg.</td><td><table><tr><td><div class="input_container"><div class="input_underlay" id="max_deg_underlay"></div><div class="input_error_underlay" id="max_deg_error_underlay"></div><textarea class="input" id="max_deg" spellcheck="false" oninput="max_deg_add(0)" onkeydown="return spinner_keydown(event, 'max_deg', max_deg_add)">3</textarea></div></td></tr></table></td><td><div class="button_group small_button_group"><table><tr><td><button class="increment pos_button fixed_button" id="max_deg_inc" title="Increment" onclick="max_deg_add(+1)">▲</button></td></tr><tr><td><button class="decrement neg_button fixed_button" id="max_deg_dec" title="Decrement" onclick="max_deg_add(-1)">▼</button></td></tr></table></div></td></tr></table></td><td class="separator"></td><td><div class="button_group"><button class="check_button" id="hold" title="Supress update" onclick="hold()">Hold</button></div></td></tr></table></td></tr><tr class="separated_row" id="expression0_0"><td class="field_name">𝑔(𝑥)&nbsp;=</td><td><table class="padding_table"><tr><td><div class="output_container"><div class="output polynomial" id="poly"></div></div></td></tr></table></td></tr><tr id="expression0_1"><td class="field_name"><span class="variable">ϵ</span><sup>2</sup>&nbsp;=</td><td><table class="horz_field_table"><tr><td><div class="output_container"><div class="output" id="poly_error"><table class="horz_field_table"><tr><td class="error_value" id="poly_error_value"></td><td class="error_change" id="poly_error_change"></td></tr></table></div></div></td><td><div class="button_group"><button class="add_expr pos_button fixed_button" id="add_expr0" title="Add function" onclick="add_expr(0, event.ctrlKey + 2 * event.shiftKey)">+</button><button class="remove_expr neg_button fixed_button" style="display: none;" id="remove_expr0" title="Remove function" onclick="remove_expr(0, event.ctrlKey)" disabled>-</button></div></td></tr></table></td></tr><tr class="options separated_row" id="flag_row"><td colspan="2"><table class="horz_flag_table"><tr><td><label class="flag_container" title="Plot legend"><table><tr><td><input type="checkbox" class="flag" id="legend" onchange="update(null, true)" checked></td><td>Key</td></tr></table></label></td><td><label class="flag_container" title="Extra accuracy"><table><tr><td><input type="checkbox" class="flag" id="extra_accuracy" onchange="update(undefined, true)"></td><td>Acc.</td></tr></table></label></td><td><label class="flag_container" title="Scientific notation"><table><tr><td><input type="checkbox" class="flag" id="scientific_notation" onchange="render_output()"></td><td>Sci.</td></tr></table></label></td><td><label class="flag_container" title="Decimal exponent style"><table><tr><td><input type="checkbox" class="flag" id="decimal_exponent" onchange="render_output()"></td><td>Dec.</td></tr></table></label></td><td><label class="flag_container" title="Ascending order"><table><tr><td><input type="checkbox" class="flag" id="poly_ascending" onchange="render_output()"></td><td>Asc.</td></tr></table></label></td><td><select id="poly_mode" title="Polynomial style" onchange="render_output()"><option value="disp">Display</option><option value="text">Text</option><option value="prog">Program</option><option value="list">List</option></select></td></tr></table></td></tr></table></td></tr></table></span><div id="status_container"><span id="status" loading>Loading...</span></div><link rel="stylesheet" type="text/css" href="https://gist.githack.com/anonymous/6059e31443745ba122dd/raw/9ca2667d0027fc4c4764533098885a8c0cc31674/poly.css"><!--[if lte IE 8]><script language="javascript" type="text/javascript" src="http://www.flotcharts.org/flot/excanvas.min.js"></script><![endif]--><script language="javascript" type="text/javascript" src="http://www.flotcharts.org/flot/jquery.js"></script><script language="javascript" type="text/javascript" src="http://www.flotcharts.org/flot/jquery.flot.js"></script><script async type="text/javascript" src="https://gist.githack.com/anonymous/6059e31443745ba122dd/raw/aa24abd74de60be00eb3d5b4cbb4e39ee8cbf3d6/poly.js"></script>

Sandbox Notes

The "no functions that perform this specific task" rule seems to be too ambiguous after all. I'm returning this to the sandbox for now.

  • 1
    \$\begingroup\$ Challenge or not, your code snippet is a mighty useful tool for math impaired people like me :). \$\endgroup\$
    – user16991
    Commented Feb 7, 2015 at 18:01
  • \$\begingroup\$ "You may not use any function that performs this specific task." But functions which perform symbolic integration, enumerate families of orthogonal polynomials, or solve systems of linear equations are ok? \$\endgroup\$ Commented Feb 7, 2015 at 18:46
  • \$\begingroup\$ @PeterTaylor I'm still mulling it over. I tried coming up with a list of no-no functions but it ended up too long. I'm aware that with the current spec Mathematica folks are going to have a field day :) \$\endgroup\$
    – Ell
    Commented Feb 7, 2015 at 19:03
  • \$\begingroup\$ Is it allowed to examine the function in ways other than numerically evaluating it? \$\endgroup\$
    – feersum
    Commented Feb 8, 2015 at 0:38
  • \$\begingroup\$ @feersum Assuming you mean something like inspecting the string or doing some symbolic analysis, then yes, that's ok. Like I said to Peter, though, I might disallow some builtin functions, like integration (symbolic or otherwise). \$\endgroup\$
    – Ell
    Commented Feb 8, 2015 at 13:06

Programming Puzzle or Code Golf?

(A judging books by covers question)

^Might need a better title.

This question is based off the "Let's Judge Some Books By Their Covers" question.

Browsing the site, I see that 1859 of our 2692 questions (69%) are tagged . My question is: what's the difference?

Your goal is to write a program (or function) to predict, given only the title of a question, whether or not that question is tagged code-golf. Your program will receive a title as input and should output either a truthy (if it's code golf) or falsey (it it's not) value.

Additionally, your program should contain no more than 1000 bytes.


The test data will be all of the questions on this website, excluding closed/migrated/deleted questions. Your score will be the Phi coefficient calculated by comparing the results of your program with the actual data. Higher values (closer to 1) are considered better.

The Phi coefficient is calculated via the following formula:

guess      puzzle  golf  total
  puzzle   A       B     Y
  golf     C       D     Z
  total    W       X

Phi = (AD - CB) / sqrt(WXYZ)

The benefit of this scoring method is that any form of random guessing (output not affected by input) results in an average score of zero.

The exact data set is yet to be generated.


I believe this challenge is an improvement over the previous challenge due to a few reasons:

  • The question title probably has a much stronger relationship to its tags than to votes, so there's hopefully more room for improvement and competition.
  • Although there will be special-casing (for words like "short") it won't be for single questions. There's no massive outliers in the data.
  • \$\begingroup\$ You might want to force the program to be deterministic to prevent return rand<.69 \$\endgroup\$ Commented Nov 11, 2014 at 15:59
  • 2
    \$\begingroup\$ Please don't change the title, it's perfect :P \$\endgroup\$ Commented Nov 11, 2014 at 16:36
  • \$\begingroup\$ This has the issue of hardcoding. A near-perfect program can probably be written by compressing the 2692 bits needed into a 337-bytes magic string and using a hash table with enough expansion to make collisions rare. Ideally, you'd have a secret test set that's separate from the training set, but I don't know how to restrict that here except for "honor system" given that the data is public. \$\endgroup\$
    – xnor
    Commented Nov 14, 2014 at 10:22

Find a Diagonal

Given a (possibly concave) polygon of n ≥ 4 sides, output a valid diagonal, a line segment joining two distinct vertices which, aside from the endpoints, is completely contained within the interior of the polygon.

For example, for the polygon

[(0, 0), (3, 0), (1, 1), (0, 4)]

a valid diagonal (in fact, the only possible diagonal) is:

[(0, 0), (1, 1)]


Some invalid diagonals are:

[(3, 0), (0, 4)]     Lies outside the polygon
[(0, 0), (3, 0)]     Is an edge of the polygon - the interior of the line is not inside
[(0, 0), (0, 0)]     Two identical vertices


Input will be n pairs of integers representing the vertices of the polygon in order. There is no fixed orientation for the input — it could be clockwise or anticlockwise. You may write either a function or a full program for this challenge, and assume any clear (all integers distinguishable) and convenient list/string format for the input.

You may assume that no three consecutive vertices of the polygon are collinear, i.e. there are no 180 degree angles. You may also assume that all coordinates are between 0 and 255 inclusive.

Output will be 2 pairs of integers representing a diagonal, which may also be in any clear and convenient list/string format.


  • You must work in the integers or rationals. In particular, you cannot use floating point integers, due to imprecision.

  • You may not use any polygon-related builtins.

  • This is code-golf, so the program in the fewest bytes wins.

Test cases

For each case, the first line is the input polygon, and the second line is all possible edges which are a valid diagonal. You only need to output one valid diagonal, and the vertices may be in either order.

Vertical diagonal
[(0, 0), (1, 1), (2, 0), (1, 3)]
[(1, 1), (1, 3)]

Horizontal diagonal
[(5, 0), (3, 4), (8, 8), (6, 4)]
[(3, 4), (6, 4)]

The relevant images are given below, in test case order (click the thumbnails to view).

Test 1 Test 2

(More cases to be added)

  • 2
    \$\begingroup\$ Your first example of a valid diagonal has one end-point which isn't actually a vertex of the polygon. The example would benefit from an image. Since you're restricting people to exact arithmetic, you should specify a bound on the vertex coordinate values so that people can work out whether they're at risk of overflow. \$\endgroup\$ Commented Mar 17, 2015 at 8:00

The Predator of my Predator is my Prey

(Three Team KotH)

Three teams: Red, Green, Blue

  • Red kills Green
  • Green kills Blue
  • Blue kills Red

As in Red vs Blue, each entrant is assigned a colour based on their userid. Your objective is to ensure your team has the most surviving members at the end of the game.

The rules are simple but the dynamics may not be obvious. For example, wiping out your prey colour early on seems like success, but it leaves your predator colour with no predators of their own, and free to wipe you out. This means early on it may be better to herd your prey rather than kill them, but this could back-fire if your team leaves it too late...

Possible game styles

Whatever the style, when a Red bot touches a Green bot, the Green bot becomes a Red bot (the bot's code is replaced by its attacker's code). The total number of bots is therefore constant throughout the game. There are a number of settings in which such a game could be played:

  • pixels in an open arena (like Red vs Blue)

  • pixels in an arena with obstacles/walls/mazes

  • bots in a continuous arena (no grid), free to turn smoothly through 360 degrees

I like the idea of a continuous arena, and bots only seeing a small radius semi-disc ahead of them. With no vision behind them they would have to either turn regularly, or coordinate with their team mates to get more information on their surroundings. Bots would be able to write messages and read the messages of other bots on the same team.

Sandbox questions

  • Stack Snippet / full multi-language KotH?

  • which of the game styles suggested would be most interesting?


ASCII Art of the Day Series

My new found love for ASCII art has lead me to a lot of good (trivial and non-trivial) ideas for ASCII ART challenges. Here are the ideas :

1. Double Knot

2. Flow Snakes

3. Chinese Shrine

4. Zodiac Signs

6. Snow Flakes

Its time for another ASCII Art of the Day. This time, we are going back to the winters and drawing Snow Flakes (not to be mixed up with Flow Snakes ;) ). The snow flakes are generative based on random walk so each run should give a different pretty snow flake ASCII.


Given an input integer N, draw an ASCII snow flake of radius N using the construction instructions provided below.


The Snow Flake will have 6-fold rotational symmetry and 3-fold reflection symmetry. You will ideally only generate 1 out of the 12 wedges in a snow flake and then rotate/mirror them to get the other wedges.

Lets consider the following snow flake for N = 5:

     \__    __/
     /_/ /\ \_\
    __ \ \/ / __
  \/ __/_/\_\__ \/
    /_/ /\/\ \_\
     __/ /\ \__
     \_\ \/ /_/
     /        \

Lets name its wedges as:

       4      3
     5\__    __/2
      /_/ /\ \_\
     __ \ \/ / __
7  \/ __/_/\_\__ \/  12
     /_/ /\/\ \_\
      __/ /\ \__
      \_\ \/ /_/
     8/        \11
       9     10

For creating the above snow flake, all we need is to first construct a single wedge (say 1) and fit others in place based on wedge 1.

Wedge Construction

Lets consider the wedges 1 and 2 from the above example and shade all the blocks which belong to wedge 1 with x.

    /2       x
   _\     xxx
  / __ xxxxx

We can see that exactly 25 x belong to wedge 1 in a 50 block trapezium of wedge 1 and 2. The height of the trapezium corresponds to the input integer N and the base length of the trapezium is 2N.

To construct the wedge 1, follow these instructions:

  • Use only the area marked for your wedge (For example, the x area in the above image for wedge 1)
  • Use uni-directional random walk to fill up the x using the characters /, _ and \
  • There should be at least 1 path in the random walk which connects the left most x with any one of the right most x of each row.

A few examples of valid random walks for wedge 1 are:


Random Ants

This is still a bit hazy but the challenge would involve making random ants out of the following ants:







Fish Aquarium

         .               `         /
                          .    ,../...       .
          .                .  /       `\  /  .
     \    .        o         < '  )     =<
     /\  .                    \ \      /  \   .  __
   >=)'>                       `'\'"'"'         /o \/
     \/ .    /         o              /,        \__/\    .:/
     /   .  /--\ /         /         <')=<     .      ,,///;,   ,;/
           <o)  =<      . / \         \`         .   o:::::::;;///
            \__/ \       <')_=<                     >::::::::;;\\\
             \            \_/            .            ''\\\\\'' ';\
    (                      \              .   __
     )                                       <'_><          (
    (          (                ,/..          `              )
     )     (    )             <')   `=<                )    (
    (       )  (               ``\```                 (      )
  • 1
    \$\begingroup\$ I like (1) and (2) more than (3) and (4) because they are more structured, so more can be done with algorithms rather than compression. \$\endgroup\$
    – xnor
    Commented May 21, 2015 at 5:20
  • \$\begingroup\$ @xnor 3 is not finalized yet, so I may do 4 before 3. But 3 would have more structure to it once done. I agree that 4 does not have much similarity, but there still is scope for reuse in 4. \$\endgroup\$
    – Optimizer
    Commented May 21, 2015 at 5:49

Sandbox note : Big change in specs, mainly for balancing issues (thanks to @trichoplax for your sugeestions :))

Major changes : Starting, Turn deroulement (2 phases from now), tie-break, Cloning. Merging may be removed due to the new specs (rendered pretty useless).

With the current specs, 1000 turn migh be WAAAAAAY to much, as you could easily go up to the 17 range... well, you could reach it in 3 turns, and with 3 turns more you could wipe everything with an explode.... Will fix that

Summoner war

tags :

You're a Summoner controlling Demons. Regulary, some tournament are done to dertermine who will be the king. And the king is always the strongest !

As it is a turn-based game, each Summoner will play twice against each opponent. So, for each pair of submission, they will all fight while playing first AND playing last.

A fight is limited to 1000 turns. A turn is the cumulated actions of both Masters.

The winner of a fight is the one who totally destroyed all the demons of the opponent. The number of Demons you killed will be used as tie-breaker

The winner of the tournament is the Summoner who won the most fights. The same tie-breaker as for fights is used, except it is the cumulated amount of kill :).

The Grid

The grid is 9*17 and the cells are placed as above :


The numbers indicates the position of the starting Demons. Each Summoner will see itself as the left Summoner. Demons can move and attack on horizontal lines, vertical lines and diagonals.


You will chose up to 6 Demons to summon, determining their stats and their capacities. You can give a maximum of 12 stat point distributed among your Demons Each Demon you summon (at this moment) will cost you 2 points.

Summoning 6 demons will cost 6*2=12 points

Summoning 3 demons will cost you 3*2=6 points, leaving you 6 points to increase their statistics.


Demons have 4 statistics :

    Hp = 2+Life
    If the hp of your Demon reach 0, it dies.
    Determine the damages you deal/heal
    Reduct all incoming damages by defense/2 rounded to superior. 
    You can't take less than 1 (except if you're attacked for 0 hit points)
    Determine the range of your attacks

Basic Moves

There's 3 moves that every Demons can do :

    The Demons will move by one unit.
    Deal damages to the Demon in an adjacent cell.
    Damages: attack+1
    Destroy the Demon and deal damages to it's surrounding.
    It only can be used if your Demon have more than 40% hp.
    It does raw damages (defense doesn't influence it).
    Damages: attack/2 (raw)
    Radius : 1+sqrt(range)  (square shaped, truncated)


Each Demon will have one capacity in the following list:

    Allows a Demon to absorb an other adding their stats 
    During the merge process, you chose if you want to keep Merge as a capacity, 
    or if you want to take the other Demon's capacity.
    After merging, a Demon won't be able to clone again.
    Heal nearby Demons but not self.
    Heal: attack/2  rounded to superior
    Radius : range+1(square)
    Deal damages on all lines or diagonals around your Demon
    It will damages on lines if the direction you specify is
    Otherwise, it will damages on the diagonals.
    Damages : attack
    Radius : range+1(lines or diagonals)
    Steal some stats if it kills the target
    The target must be on an adjacent cell.
    Damages : attack
    Stat stolen : range (maximum)
                The stat stolen will be distributed randomly between the stats
                of your Demon. It cannot steal more point that the opponent 
                Demon have.


You may give an optional name for your Demons. This name will only be known by you, and could be useful if you want to remember the role you gave to your Demons. This name could be changed at anytime.

Turn deroulement

Each player's turn has 2 steps : the enhance phase and the battle phase.

A turn is derouling as following :

player 1's enhancing phase
player 2's enhancing phase
player 1's battle phase
player 2's battle phaes

Enhance phase

Each turn, you will be given 6+nbTurn/50 stats points.

On turn 1, you will have 6 points.
On turn 50, 7 points. 
On turn 1000, 26 points. 

Those points will stack upon time if you don't use them.

On turn 1, I had 6 points, I used 4 remain :2
Turn 2, I gain 6 points more, I can use 8.
etc ...

Those points can either be used to increase the stats of your Demons (1 point = 1 life||attack||defense||range) or to clone them.

To clone a Demon, you must use 2+life+attack+defense+range points. In result, the origin demon will have his points halved, and a clone with the other half will spawn.

Let's say I want to clone the following demon :
He has 2+2+5+0 = 9 statistics points, so I would need 2+9=11 points.
The resulting Demons would both be :
 defense=3 (yes, stats are rounded to superior :))

Battle phase At the start of the battle phase, you will be given :

  • The current tableboard
  • A list containing your Demons and all the information about them
  • A list containing the stats and position of your opponent's Demons

You will return the actions of all your Demons.

you have up to x ms to return this list (not decided yet)

Once you've chosen your actions, the following will happen :

  • Every Demons which had to move, will move. If two Demons try to move to the same location, they will both stay still.
  • All the actions which change the hp(heal/damages) will happens at the same time.
  • Finally, your turn end, and your opponent's will decide his actions.


Each submission will be written in Java. You can't interact with other players nor the controller in any way you could imagine.

You must extend the following class :

Class not yet developped

A github link will be provided, for the controller etc.

Sandbox notes

I'm aware that there's plenty typos and errors, I will correct them before the final version. Some text and clarification might be added. As it can be complicated (lot of options), 4 demonstration Summoner will be provided (and will be in the pool), each of them using only some functionnality (prooving that you don't have to use every single thing).

I'm not done yet with all the sources for the controller/field etc. An API will be provided for extracting/using informations easily. Once it will be complete, I will put a time limit for the execution of one turn. If I have time, I will provide an interface to see the fights with colors etc.

Questions :

  • Is this too complex? I'd like to know if to much options are given, and if it's confusing (ie, if you don't know where to start).
  • Is there some points of the ruleset that are obviously dangerous for the good health of this contest.
  • Any suggestion?

Thanks for reading :)

  • \$\begingroup\$ I've removed all <code></code> tags and instead selected the code and pressed ctrl-K (which adds 4 spaces before the code). This formats as a code block, instead of a series of code lines with white gaps between. I find this much easier to read so I've edited it in for you to see, but feel free to rollback to the previous edit (I thought it would be easier to edit and show, rather than try to describe). \$\endgroup\$ Commented Jun 5, 2015 at 11:02
  • \$\begingroup\$ Ho, thank you, did not know the K^ thing ! I didn't think it was hard to read with it, that's why I did put <code> instead of spaces. Anyway, thanks :). \$\endgroup\$
    – Katenkyo
    Commented Jun 5, 2015 at 11:11
  • \$\begingroup\$ You're welcome :) \$\endgroup\$ Commented Jun 5, 2015 at 11:37
  • \$\begingroup\$ @Katenkyo I'm not certain but wouldn't it be possible just to fill the whole grid by cloning? Which would make it quite hard to develop an effective strategy (because clone leaves two demon with potentially full health- it might work if it shares the health between the clones)- or is that the idea (make a massive army of demons and then fight? \$\endgroup\$
    – euanjt
    Commented Jun 5, 2015 at 14:14
  • \$\begingroup\$ @TheE I think the AoE could compensate this point. One Demon with a good attack stat (via merging/eating) could one-shot a big number of your Demon/turn. I want the "fill with clones" strategy to be possible, but with a little more thinking to be competitive. I don't know yet if it is owerpowered. Anyway, it have to be tested ! Thanks for the case, didn't think of it. Will test it as soon as the controller is up. \$\endgroup\$
    – Katenkyo
    Commented Jun 5, 2015 at 14:29
  • \$\begingroup\$ Minor point: the list of standard moves still refers to 4 instead of 3 moves. \$\endgroup\$ Commented Jun 22, 2015 at 14:09
  • \$\begingroup\$ Explode affects a radius of 1 + sqrt(range). Is this a square range or some other shape (Euclidean to give an approximate circle?). Is the sqrt rounded up or down? \$\endgroup\$ Commented Jun 22, 2015 at 14:11
  • \$\begingroup\$ square range, round down (so 16 range will effectively add 4 points) I did that because you'd only need 17 range to wipe out the entire map with raw damages... No you still can have a good range, but it's harder \$\endgroup\$
    – Katenkyo
    Commented Jun 22, 2015 at 14:13
  • \$\begingroup\$ What if the cross affected both players (so you need to get into the right position or else accept that some of your own demons will be hit too)? Would that be interesting or just awkward? How would it affect the balance of the different capacities? \$\endgroup\$ Commented Jun 22, 2015 at 18:35
  • \$\begingroup\$ What if explode and heal also affected both players (all demons in range)? \$\endgroup\$ Commented Jun 22, 2015 at 18:36
  • \$\begingroup\$ @trichoplax I'm thinking about it since the beginning, but I am not able to make my mind about it... I mean, sure it is interesting, and all but... Isn't it too much? You already have to manage lots of demons, to buff/clone them, be aware of your opponents. So I don't know, I can't know, if that would be too difficult to handle... \$\endgroup\$
    – Katenkyo
    Commented Jun 22, 2015 at 18:48
  • \$\begingroup\$ I was thinking less about how complicated it is and more about whether it would make the capacities more balanced. I think the main problem would be if one of the capacities is too strong and everyone chooses nothing else. \$\endgroup\$ Commented Jun 22, 2015 at 21:55
  • \$\begingroup\$ @trichoplax sounds logic. I'll look at a way to implement it :) \$\endgroup\$
    – Katenkyo
    Commented Jun 23, 2015 at 5:32

Ironclad Tactics KoTH

This KoTH is inspired by the Ironclad Tactics paper version from Zachtronics.

The game is played on a 9x4 grid split into three areas: the North, the South, and No-Man's-Land (the center). To make things easier for you, it will always appear that you are the North (the left).


Each battle, each player starts with 10 Action Points (AP). In a battle, there are 4 phases: Selection, Placement, Upgrading, then Attacking.


During selection, players start by each simultaneously choosing an upgrade to ban, and then choosing 5 of the 8 or 9 remaining upgrades they wish to use. The chosen upgrades are not revealed to their opponent.


During placement, players simultaneously place an Ironclad until they decide to drop out of the phase or they have used all of their AP. Each placement costs 1AP, and Ironclads can only be placed on the player's respective side and No-Man's-Land.


During upgrading, players simultaneously upgrade one of their Ironclads using their remaining AP until they decide to drop out of the phase or they have used all of their AP. Each upgrade costs 2+(# of times you previously used the upgrade)-(# of times your opponent previously used the upgrade), with a minimum cost of 0.

There are 10 possible upgrades:


The stars represent Ironclads, and each circle represents the squares the Ironclad will attack. The arrow represents the Saboteur upgrade, which will give the player 2 additional victory points, and the diamond represents the Heavy Chassis upgrade, which requires 2 hits to be destroyed.

Upgrades can be given to any of your unupgraded Ironclads, even if the squares it would attack fall off of the board. Upgrades do not need to be given to all Ironclads.


During attacking, all Ironclads simultaneously attack. Any Ironclad in the square of attack (even if the attack is friendly) is destroyed (unless the tank has the Heavy Chassis upgrade, in which case it must be attacked by two different tanks.

Any remaining tanks give 1 (or 3, if the tank has the *Saboteur upgrade) victory point(s) if they have a horizontal line of sight to the opposite end unobstructed by undestroyed enemy tanks.


You will implement a Java class. more info

Additional Info

  • You will have 10 battles against each opponent.
  • The price for upgrades resets after each opponent.
  • You beat an opponent by having more victory points than them after the 10 battles. You win this challenge by beating the most opponents.
  • If both players attempt to place in the same spot at the same time, that location becomes unplaceable for the rest of the battle, and players must place again.
  • -


You are the proud maintainer of one of the smartest robots in the world. Well, it used to be. Now its speakers and microphones have been broken and the darn thing only seems to read Brainfuck. To make matters worse, it would appear most of its RAM... disappeared? This will be tough to explain to the boss. No matter. It seems to have figured out how to draw on a whiteboard to supplement its now-shoddy memory, and you have bigger problems on your hands.

You need to know how to fit things in cubes.

The Task

Lately, your biggest problems (aside from the embarrassing conversation with your boss later) have to do with volume. Cubing things is hard. That's why you'll get the robot to do it for you! Your goal in this challenge is to write a Brainfuck program that computes the cube of a given number. However, the robot's whiteboard isn't very big. The less memory your Brainfuck program requires, the better.


You will receive a single integer as input, x.

  • You may choose to accept input in any integer base greater than 0 and less than or equal to 36, so long as this base does not vary from input to input. (e.g. binary, hexadecimal, decimal)

  • You may assume that x is in the range 0 <= x <= 2^16 - 1

  • You should take input as a string of characters, not bytes. For example, if x = 33 and my program accepts input in binary, I should receive the string "100001" (bytes: 49 48 48 48 48 49) not simply bytes containing 100001.


  • Your Brainfuck program must output the value of x^3 in the same base that input was received in.

  • As it is for input, your program should output a string of ASCII characters, not a sequence of bytes.

  • The program must terminate, and should not print anything except for its numerical output.

Rules and Scoring

Your score in this challenge is defined in the following manner: Let the tape of the Brainfuck memory be described as having a 1st element at the left-most position, and then with potentially infinite cells to the right, indexed by increasing integers n.

Let N(x) denote the right-most (highest n) cell that the program ever sends the tape pointer to (not necessarily modified) for a given input x. Your score for this challenge is then sum (x = 0, 1, 2, ... 100) N(x) (modification pending)

In order to verify score, you may use [this] (soon) modified interpreter.

  • Your program must be written entirely in Brainfuck.
  • Assume the highest value a cell can hold is 255 before wrapping to 0, and that moving left off of the tape will cause the robot to suddenly and violently crash.
  • Your program should not exceed 10k bytes, nor should it take more than 10 minutes to compute x^3 for any x <= 2^16 - 1 on a relatively modern machine.
  • Standard loopholes are disallowed.


What do you think of BF memory-optimization as a basis for a challenge?

I chose cubing x as a challenge that is not so trivial as to allow for different approaches, but still within the grasp of BF (if different bases are allowed). Any other ideas?

  • 1
    \$\begingroup\$ How is the base determined? For example, if the input is 2, how is it determined if that's base-10 (and so output 8) or base-8 (and so output 10)? \$\endgroup\$ Commented Nov 5, 2015 at 20:50
  • \$\begingroup\$ My thought was along the same lines as TimmyD: the obvious cheat is to just read the digit, write it, and then write 00 and claim that the input was in base x. \$\endgroup\$ Commented Nov 5, 2015 at 21:48
  • \$\begingroup\$ @TimmyD Ack! My post is unclear. I meant that you, as the programmer, may choose what base you expect your input/output to be in. e.g. I can write a BF program that accepts input in base 16 and outputs in base 16, or use ternary if I think it'll help me use less memory. I didn't mean that the base changes from input to input. Thank you for the feedback, I'll certainly try to clear that up! \$\endgroup\$
    – BrainSteel
    Commented Nov 6, 2015 at 1:48
  • \$\begingroup\$ What is the largest allowed input base? Also, the maximum input needs to be bigger: the current rules probably allow hardcoding of all the outputs. \$\endgroup\$
    – feersum
    Commented Nov 6, 2015 at 2:08
  • \$\begingroup\$ @feersum Good points. I'll cap it at 36 to avoid the general silliness of trying to figure out what symbols to use. I understand your concern, but I want to keep the upper limit fairly small. I think 2^16 - 1 should do the trick? \$\endgroup\$
    – BrainSteel
    Commented Nov 6, 2015 at 2:27
  • \$\begingroup\$ @BrainSteel That should be good enough, as long as there are some test cases throughout the range. \$\endgroup\$
    – feersum
    Commented Nov 6, 2015 at 2:31

Pi, continued

The task: generate an arbitrarily precise rational approximation to pi by using a continued fraction.

One way to calculate pi is by using this continued fraction (from Wikipedia):

enter image description here

The first few approximations can be calculated as follows:

enter image description here

enter image description here

enter image description here

enter image description here

You may not use this particular continued fraction. The reason is that in order to calculate this sequence to arbitrary precision, you have to already know pi to arbitrary precision. The series [3,7,15,1,292,...] does not repeat, like pi's own digits.

However, there are continued fractions that have a regular structure. You may use any of these you wish (like these on Wikipedia) in your program.

The rules

  • Input: a single, non-negative integer n.
  • Output: the nth (improper) fraction in your chosen continued fraction series, in lowest terms.
  • Output may be in any form, provided that these conditions are met: 1) the same base is used for numerator and denominator (and for all fractions), 2) the numerator and denominator are clearly distinguishable, and 3) the numerator comes first.
  • Your program must use a continued fraction. It may not use any summation series like the approximation formulae here on Wikipedia.


  • I feel like some of this may be confusing. What can I clear up, and how?
  • Is it misleading to introduce continued fractions by using an unpredictable series when I want users to use ones that have a regular structure?
  • \$\begingroup\$ It looks good to me. As long as you don't mind the example being valid for use in an answer, yes it does seem to make sense to use one of the regular structured ones for the example. That way someone who doesn't read it properly can just use the example without realising there are other options, and you get fewer annoying questions... \$\endgroup\$ Commented Nov 18, 2015 at 2:20
  • 2
    \$\begingroup\$ Yes, it is misleading to start with the unpredictable series. Are you ruling out approximating pi with a built-in or other limit (that is not a summation), then computing the continued fraction from that? The examples you link are generalized continued fractions, which can have numerators other than 1 and summands that are not whole -- I take it those are allowed? \$\endgroup\$
    – xnor
    Commented Nov 18, 2015 at 9:24
  • 1
    \$\begingroup\$ The nth term in a continued fraction series is well defined modulo possible out-by-one disagreements in the indexing. But for generalised continued fractions, there are three competing definitions: if the gcf is x = b_0 + a_1 / (b_1 + a_2 / (b_2 + ... )) is the sequence b_0, b_0 + a_1, b_0 + a_1 / b_1, b_0 + a_1 / (b_1 + a_2), b_0 + a_1 / (b_1 + a_2 / b_2), ...; or is it b_0, b_0 + a_1 / b_1, b_0 + a_1 / (b_1 + a_2 / b_2), ...; or is it b_0 + a_1, b_0 + a_1 / (b_1 + a_2), b_0 + a_1 / (b_1 + a_2 / (b_2 + a_3)), ...? \$\endgroup\$ Commented Nov 18, 2015 at 19:44
  • \$\begingroup\$ Regarding the competing definitions, I think the cleanest resolution would be to allow any pattern that adds one layer at a time in a consistent fashion, which allows any of the examples as well as off-by-one disagreements. \$\endgroup\$
    – xnor
    Commented Nov 18, 2015 at 22:09

Rotate / Flip a Unicode Box Drawing

Given a Unicode box drawing, followed by a series of rotate and/or flip commands, output the result of those operations on the drawing. For clarification, a box drawing can be made from the following characters:

─ │ ┌ ┐ └ ┘ ├ ┤ ┬ ┴ ┼
═ ║ ╔ ╗ ╚ ╝ ╠ ╣ ╦ ╩ ╬
    ╒ ╕ ╘ ╛ ╞ ╡ ╤ ╧ ╪
    ╓ ╖ ╙ ╜ ╟ ╢ ╥ ╨ ╫

The rotate and flip commands are also presented using Unicode symbols:

↔  Flip the drawing horizontally
↕  Flip the drawing vertically
↷ Rotate the drawing 90° clockwise
↶ Rotate the drawing 90° counter-clockwise
↯  Convert all single lines to double and vice versa (Optional - 10% bonus)

All other characters should remain unchanged, but moved to fit where they would be in the modified drawing. For example, if given the inputs:

Input   Output          Input   Output
 ┌┴╖     ╓┴┐             ┌┴╖     ╔═╕
 │A║     ║A│             │E║     ╣E├
 ╘╦╝     ╚╦╛             ╘╦╝     ╙─┘
 ↔                       ↔↷

 ┌┴╖     ╒╩╗             ┌┴╖     ┌─╖
 │B║     │B║             │F║     ┤F╠
 ╘╦╝     └┬╜             ╘╦╝     ╘═╝
 ↕                       ↷↔

 ┌┴╖     ╓─┐             ┌┴╖     ╔╩╕
 │C║     ╣C├             │G║     ║G│
 ╘╦╝     ╚═╛             ╘╦╝     ╙┬┘
 ↷                      ↶↶

 ┌┴╖     ╒═╗             ┌┴╖     ╔╩╕
 │D║     ┤D╠             │H║     ║H│
 ╘╦╝     └─╜             ╘╦╝     ╙┬┘
 ↶                      ↔↕

The drawing may be of any size (let's say anywhere from 1×1 to 50×50), and not necessarily square.

The flip and rotate commands will always occur after any drawing to be flipped, and by themselves on one single line. They should be executed from left to right. (Note that order matters - the E and F examples use the same two commands but in reverse order, and produce different results.)

There may be an arbitrary number of flips and rotates, but you'll note that there are only 8 possible end-states for the final drawing. The G and H examples show two different sets of commands that produce the same result (other than the letter in the middle). It is possible that a series of commands will result in simply returning to the original drawing.

Input may be supplied via command line, user input, file I/O, or any other means you see fit. (Though it should obviously support multiple lines of input. You may use \n to represent line breaks if your input mode only supports a single line.) Likewise, output may be to the screen or a file at your discretion.

This is code-golf, so shortest code wins.

Some more complicated examples:

Input    Output        Input    Output
          ┌─┐                    ┌─┐
          │A│                    │B│
┌─╥─┐     ╞═╡          ┌─╥─┐     ╞═╡
│A║B│     │B│          │A║B│     │A│
└─╨─┘     └─┘          └─╨─┘     └─┘
↷                     ↶

   Input           Output
┌─┐╔═╗╒══╓──    ──╖══╕╔═╗┌─┐
├─┘╠═╝│  ║ ╖    ╓ ║  │╚═╣└─┤
│  ║  ╘══╙─╜    ╙─╜══╛  ║  │

┌─┐╔═╗╒══╓──    ╔═╗┌─┐╓──╒══
├─┘╠═╝│  ║ ╖    ╠═╝├─┘║  │ ╕
│  ║  ╘══╙─╜    ║  │  ╙──╘═╛

┌─┐╔═╗╒══╓──    ┌─┐╔═╗╒══╓──
├─┘╠═╝│  ║ ╖    ├─┘╠═╝│  ║ ╖
│  ║  ╘══╙─╜    │  ║  ╘══╙─╜
  • \$\begingroup\$ You should have examples where characters other than the box move, the box is a different size and with more than one box, if that is allowed. This looks like a good challenge, but one that is likely to be rife with ambiguity. \$\endgroup\$ Commented Dec 9, 2015 at 14:46
  • \$\begingroup\$ @FryAmTheEggman - I chose one starting box which is asymmetrical just as a simple example. I could add a couple more complicated shapes - I was thinking this could be applied to any shape using the box-drawing symbols, not just a simple box. \$\endgroup\$ Commented Dec 9, 2015 at 18:55

Create a spiraling image




Given an image, output the image with a spiraling effect.


This is a , so the submission with the highest number of votes wins!

Test cases

Note that your program should work for images with any size. The output should be a 512×512px image. Also, note that the test cases are examples, you may use any algorithm to produce these images and do not have to match the images below. Use your creativity!

Test case 1

enter image description here


enter image description here

Test case 2

enter image description here


enter image description here

Test case 3

enter image description here


enter image description here

Test case 4

enter image description here


enter image description here

Test case 5

enter image description here


enter image description here


The full size images:

  • \$\begingroup\$ What counts as the Droste effect does not appear to be clearly defined here, and some of the example outputs are hard to justify as exhibiting the effect. The chat image in particular doesn't seem to have any repetition of the image within itself, only distortion of the scale. \$\endgroup\$ Commented Feb 13, 2016 at 23:23
  • \$\begingroup\$ @trichoplax Oh, you're right. That isn't even a Droste image. I should probably remove the "Droste" thing and make something else out of it. Maybe define it as a "spiral" image. \$\endgroup\$
    – Adnan
    Commented Feb 13, 2016 at 23:30
  • \$\begingroup\$ Either way it sounds like the too-broad end of the popularity contest spectrum. For a Droste image challenge you could probably make it well defined enough to not need to be a pop con if you also have a template as input, defining one or more places where the image needs to reappear recursively. So for each hole in the template, the image will reappear, including the holes in the template for repeatedly smaller images. \$\endgroup\$ Commented Feb 13, 2016 at 23:33
  • 2
    \$\begingroup\$ @trichoplax Hmmm, okay. I should give this a lot of thought then. I do think that with the amount of possible ways to approach this problem, this should be a popularity contest. But it's definitely too broad at this stage. \$\endgroup\$
    – Adnan
    Commented Feb 13, 2016 at 23:41

Random Physics Golf #1: Net Gravitational Force

Introduction to the Series

Every week or so I will be posting a physics challenge. My goal here is to design challenges that in the end, teach some people some physics. Overall, the challenges will be very basic with little information. All of these challenges will have the minimal information necessary to solve them, and the goal is for users like you to do some research, watch some videos, and understand how these concepts work to teach you how to approach these types of physics problems and explain how they work. Of course, I will also give two optional hints per challenge, which are there if you do not have the time or determination to do the research, or you cannot figure out how to do the problem after researching. The two hints will be "necessary equations for this challenge" and "process to solve the problem". The hints are completely optional to use and it is encourages to not use them, but as stated above to learn the information for yourself. The series will have one main leaderboard. Whoever has the least combined byte count for all of the challenges gets a to be determined prize. Each challenge will range in difficulty, with an upwards trend of difficulty. I wish you all luck and I hope you learn a thing or two!

Challenge #1: Net Gravitational Force

Note 1: this challenge highly requires knowledge of the mathematical vector quantity, if you do not know what that is, I suggest reading this and this before attempting this challenge.

Note 2: this challenge considers gravity in CLASSICAL MECHANICS. Disregard general relativity for this challenge.

Lets start with the definition of a force. A force is a vector quantity, a number with both direction and magnitude. Simply put, force is mass times acceleration. Many mathematicians will know the name of this formula as Newton's Second Law. Now, that is a well known formula, but here is something less known: all forces are classified in one of four categories: weak nuclear, strong nuclear, electromagnetic, and gravitational. These four are called the four fundamental forces of the universe. We will be focusing on the gravitational force in this called.

The gravitational force is then classified as a field force. This means that the force acts on all objects in a certain radius around another object. In this case, gravity pulls down on objects from anywhere in a radius around them. However, I still have not defined where gravity comes from. Well, the simple answer is from mass. An object with more mass has a bigger gravitational pull on objects around it. In case you are wondering, the earth has a gravitational pull of -9.81 m/s^2 (an object will gain 9.8 m/s of downward velocity every second). But here is where it gets fun: because gravity comes from mass, every object with mass has a gravitational pull. This is where you come in. I want you to calculate the net gravitational pull of all the objects surrounding another object. Here is a better explanation:

You will receive co-ordinates and masses of objects in space for input. So an example input could be visualized as this: enter image description here You can easily see each force being applied on the target object by the three larger objects. Objects will smaller masses have a smaller gravitational field (as shown by the orange force arrow). Your job in this challenge is to find the net gravitational force being acted on the target object. To do this, it is a simple vector addition problem with the forces from the other objects. So, the resultant vector (net force), may look something like this: enter image description here This is all of the information that I will give you. It is now your job to find the equations, and research how this all works.

Challenge Specs

  • Input will be several lists of numbers consisting of the x co-ordinate, y co-ordinate, and mass of each object. The numbers could be either integers or decimals. You may take this in any convienent format ([[1 2 3][4 5 6][7 8 9], [(1,2,3),(4,5,6),(7,8,9)] and 1,2,3|4,5,6|7,8,9 are all acceptable. The first list of inputs will always be the target object (red in the pictures above), and the other lists will be the other objects. All inputs will have at least two objects. No objects will have the same co-ordinates.
  • Output will be two numbers, in any human-readable format, in any order. One will be the magnitude of the net force, using your desired unit system (SI, Planck units, Imperial units, etc.) and the other will be the direction in radians OR degrees of the net force. Output must be precise to the least number of significant figures in the input (Input: 2, 3.5, 6.1 -> Output: 200 (232.34 before rounding), note this is not an actual test case). Output may or may not be in scientific notation, its up to you.
  • You may assume input will not cause any error during execution, and you may assume all inputs will be valid.

META NOTE: Help me decide the precision of the output: http://strawpoll.me/6825341

Test Cases

Meta Note: WIP


These hints are for those who do not want to put in the time and effort of research, or those who could not find a solution. So, here are the two hints:

Hint 1: Equations:

You need the following equations for this challenge:

enter image description here

You will also need the standard vector equations for this challenge:

enter image description here

Hint 2: Sample Solution Process:

It would take up too much space to fit it all here, so I made this to aid you for this hint.


Meta Note: blah blah blah, working leaderboard will eventually go here! This leaderboard will contain and combine scores for all of the weekly challenges. It will only be visible on this question, though.

  • 1
    \$\begingroup\$ The input format currently is cumbersome, requiring string parsing. I would recommend loosening it to allow input as a list of 3-tuples (or similar representations). You should also specify whether the inputs will be integers or decimals. \$\endgroup\$
    – user45941
    Commented Feb 5, 2016 at 3:45
  • \$\begingroup\$ @Mego I took your recommendations. Does that look good? \$\endgroup\$
    – GamrCorps
    Commented Feb 5, 2016 at 21:55
  • 1
    \$\begingroup\$ "Output must be precise to at least three decimal places" would get a rebuke from every physics teacher I ever had. Surely it should be to a number of significant figures which depends on the s.f. of the input? \$\endgroup\$ Commented Feb 6, 2016 at 13:45
  • 1
    \$\begingroup\$ @PeterTaylor Well, this is a programming challenge, and sig-fig calculations would (IMO) overly complicate the answers. (If your comment was a joke/sarcasm sorry ;) \$\endgroup\$
    – J Atkin
    Commented Feb 13, 2016 at 19:56

Temperature in a line of rooms

You have a line of rooms that are different temperatures.

      1       2       3  
 1.2  |  3.5  |  4.0  |  3.7

The doors between adjacent rooms start out closed. When you open a door, the now-connected rooms average out their temperatures. For example, opening door 2 gives

      1       2       3   
 1.2  |  3.75 _  3.75  |  3.7

Then, opening door 1 equalizes the first three rooms to their average (1.2+3.75+3.75)/3 = 2.9

      1       2       3   
 2.9  _  2.9 _  2.9  |  3.7

Finally, if we close door 2 and then open door 3, the last two rooms will average out without affecting the other rooms.

      1       2       3   
 2.9  _  2.9 |  3.3  _  3.3

You can think of the instructions to open and close doors as a sequence of toggles that switch between open and closed, here 2, 1, 2, 3, with the doors starting closed. Given the initial temperatures of the rooms and the sequence of door toggles, output the final temperatures. Fewest bytes wins.


  • A list of initial room temperatures, which are positive reals. There will be at least two rooms.
  • (Optional) The number of rooms n.
  • A list of doors to toggle in order, which range from 1 to n-1. Optionally, these may be zero-indexed.

Output: The list of final room temperatures to some reasonable precision.

TODO: Test cases.


Senior Prank

We're graduating to a full site soon, and there's only one thing left to do before graduation: pull a senior prank! I think we should do a variation on the classic "fill a hallway with cups of water" gag.


Your program will read in text and output that text, covered in upside-down cups of water. An upside-down cup of water looks like this: /~\
These cups can only be placed in whitespace in the input, and can only be placed so that all three characters of the cup are directly above a non-whitespace character (otherwise the water would spill out!). Cups cannot be stacked on top of other cups. Cups must be placed in every available opening, and it is assumed that every input is surrounded by an infinite field of whitespace.
We need to pull the prank off quickly and without anyone noticing, so fewest bytes in each language wins.

Test Cases


    /   ___    /   ___    /   ______/   ________/
   /   /__/   /   /__/   /   /     /   /_______
  /   _______/   _______/   /     /   //__    /
 /   /      /   /      /   /_____/   /___/   /
/___/      /___/      /_________/___________/


    /   ___    /   ___    /   ______/   ________/
   /   /__//~\/   /__//~\/   /     /   /_______
  /   _______/   _______/   //~\  /   //__    /
 //~\/      //~\/      //~\/_____//~\/___//~\/
/___/      /___/      /_________/___________/


 L\\        ____I____
    ========    |  |[\


 L   /~\/~\/~\/~\/~\/~\/~\
 L\\/~\/~\  ____I____
    ========/~\ |  |[\
  • \$\begingroup\$ @TimmyD Initially that gap was two wide. I must have added the space after making the output. \$\endgroup\$ Commented Mar 3, 2016 at 18:19
  • \$\begingroup\$ @FryAmTheEggman Yeah, that's a typo. I should really double check when I edit on my phone. \$\endgroup\$ Commented Mar 4, 2016 at 4:39

City Life

A cellular automation war game.

In this game, each player will control group of cites on a grid. Each city takes up one cell, and all cells with no city are "wilderness", and have no owner. The game will consist of a series of rounds, called "generations". Play continues until a player gets 1000 points, or 200 rounds, whichever happens first.


The board will start with one city controlled by each player. It will be square with sides length ceil(sqrt(25*n)) for an n player game. Cities will be placed randomly in such a way that no two cities will see each other the first round.

Phase 1: give orders

At the start of each generation, each city gets n actions where n = # of adjacent wilderness spaces + 2. So a city surrounded by wilderness gets 10 actions while a city surrounded by cites gets only 2. The Actions will be divided into these three categories:

Attack/Spread : used to Attack Cites or spread into the wilderness.

  • Takes a direction as a parameter. Will add one "Attacker" to that cell, even if the cell is a city with the same owner. (See resolve attacks)

Defend : used to protect your city.

  • Will add one to the defender count of the city performing this action. (If no defend actions are used, the city will become wilderness.)

Score : used to win.

  • Adds one to the score the cites owner.

Phase 2: resolve attacks

After all cites have put in orders, all cells are checked for takeover.

  • A wilderness cell will become a city if at least three attackers are there. The new city's owner will be determined randomly from among the attackers.(for example, if player A sent 2 attackers and player B sent 3, than A has a 2/5 chance of owning the new city)

  • A city will become wilderness if the number of attackers is equal to the number of defenders (even if both are 0).

  • A city is taken over if their are more attackers than defenders. The city's new owner is determined randomly from among the attackers, as above.

After the round is complete, all attackers and defenders are reset.

To enter the competition, you must create a bot to perform the "give orders" step. All bots will be written in JavaScript.


You will provide a character to represent your city and a function that takes as parameters:

  1. Your vision. each city can see a 5x5 square with the city as its center. It will be represented as an array of arrays of characters, " " representing wilderness, and each players character to represent their cites.


if you have a map like This ("Y" represents you)

|AA  B|    N
|A    |    ▲
|  YY | W< O >E
|C   C|    V
|   C |    S

Your sight parameter will be:

[["A","A"," "," ","B"],["A"," "," "," "," "],[" "," ","Y","Y"," "],["C"," "," "," ","C"],[" "," "," ","C"," "]]`
  1. The number of actions you can perform this turn. (which can be calculated, but I will give it to you as most bots will need it.)

You must return an array of strings, each string representing an order.

"N" - Attack North

"NE"- Attack North east

"W" - Attack West


"D" - Defend

"$" - Score

If you return more moves than you have actions allotted, the moves at the end of the array will be ignored. If you have less, extra moves will be set to "D".

I have made a controller that is reasonable, although I would like add to it and finalize the rules before publishing. If you have any advice or criticism, please comment below.

Example Answer:

Random Bot [?]

function(map, moveCount){
    var allMoves = ["N","S","E","W","NE","NW","SE","SW","D","$"];
    var orders = [];
    while(orders.length < moveCount){
    return orders;

This bot will just assign a random move for each action. Its cites are represented by ?.

  • \$\begingroup\$ I think you left off a row in the map. You should also clarify whether attackers and defenders are persistent or must be re-assigned each turn. \$\endgroup\$
    – ballesta25
    Commented Jan 18, 2016 at 20:15
  • \$\begingroup\$ "A city can become wilderness if the number of attackers is equal to the number of defenders" implies to me that there's a random element. Is that so? If not, I suggest replacing can with will. \$\endgroup\$ Commented Jan 23, 2016 at 19:08
  • \$\begingroup\$ @PeterTaylor Thank you, fixed. \$\endgroup\$
    – MegaTom
    Commented Jan 23, 2016 at 20:52
  • \$\begingroup\$ I've been thinking more. It would be good to state the initial density (or, in other words, how the size of the world varies with the number of players). In the interests of fairness, probably also worth guaranteeing that the initial cities will have a certain buffer region (and in particular, that two of them won't start next to each other and a third in a nice open space); and that the topology will be toroidal (so the board wraps both horizontally and vertically). Finally, I would make it explicit that you can attack your own city, but not "support" it (i.e. lend it defenders). \$\endgroup\$ Commented Jan 23, 2016 at 22:25

Super Smash Bots

This is an idea for a KOTH based off of the Super Smash Bros video game series by Nintendo.

The basic mechanics of this KOTH would be an every-man-for-himself battle between a large number of players simultaneously. Players can execute a variety of moves, like short/medium/long-ranged attacks or blocking. As opposed to most combat-based games, players do not have a health bar, but rather die when knocked off of the stage (the arena). When an attack hits a player, it deals damage to that player but also causes knockback. The amount of knockback a player experiences is proportional to the total amount of damage he's received so far in the game.

The Arena

The game takes place on a vertical stage with gravity. There will be several fixed platforms surrounded by empty space. A player too far from a platform is killed. More ideas about the design of the stage are covered in the Stage Design section.

Character Selection?

The actual game offers players the selection of different characters, each of which have different abilities, strengths, and weaknesses. If I am to include character selection, that will be a way for players to pick the strategy they think works best and choose a bot that has those strengths. Another KOTH which had this feature was the Pokemon-themed KOTH (citation needed).

On the other hand, balancing stuff can be hard.


  • Move. Simple as that. Well, not exactly. I think this could make a very good contender for a continuous-surface (not a grid) area. On a surface, the character would walk, while airborne, the character's movement doesn't respond as quickly.
  • Jump. Is like a move, but vertical. More specifically, this gives the player an upward velocity. Double jumping might be possible.
  • Short Range. This deals damage to an immediately adjacent player.
  • Medium Range. This deals damage to players within a certain range. It would likely involve your player physically moving as well.
  • Long Range. This creates a projectile, which can deal damage to a player in the specified direction, no matter the distance.
  • Area of Effect. All players within a given range take a little damage.


Is is often typical that players have three lives, and thus must be killed three times to be eliminated. By respawning players, the variance of each match outcome should be reduced.

Game Ticks

If I'm doing a continuous-field, then I would want something the emulates continuous movement. In order to give fair processing time, I can't really have all of the entrant programs running at once in an asynchronous fashion. Some possible solutions are as follows.

  1. Priority Queue
    • Each action taken creates a certain time delay before the player can move again. Standing still is shortest delay, moving is second-shortest, and long-ranged attacks have the longest delay.
    • Turn order is determined by a priority queue. From the list of players, the player with the least delay is selected. Then, the game's physics are simulated for that amount of time ("virtual" time, not "true" time) and that much time is subtracted from everyone's delay. The selected player picks an action, and he is put back into the queue with that move's delay.
    • This creates a period of vulnerability after an attack which may be game-mechanically interesting.
  2. Random Time-Steps
    • Play occurs in a semi-random order, with random, non-uniform time-steps between moves. This makes it so that the player cannot predict exactly what the world will be like in the future, or guarantee the exact timings of any moves.
    • After each player has taken a single move, the order of players would be scrambled.
    • Time-step duration would be approximately constant with a random variation of +/-20% or something like that.


This would be really cool to watch, but I don't think I could possibly animate this by myself.

Stage Design

Stage design will be important, because a large chunk of the entrant programs will be tailored the stage. I don't really have any clue what I'm doing here.

One idea I've had is to crowd-source the stage design.

Maybe something with a few ledges, like this? (scaled down for ASCII-artability)


I could add some more features like so:


The slants represent ramps that the player could walk up.

Player Navigation

I foresee one of the most difficult things for entrants to do is to navigate the stage. Each player would definitely receive a copy of the current stage and players as input every turn (or as arguments/parameters, more details on that below).

I may choose to offload a bunch of pathfinding stuff onto the controller so that entrants, if they so desire, can give the destination and have their character move there. Given that the stage would be constant, this should not be difficult for the controller to do. On the other hand, the continuous-field design can make pathfinding more complicated.

One thing to consider during stage design is the ease of pathfinding.

Vertical or Horizontal?

Pretty much the whole proposal has been assuming a vertical map. I could change this to horizontal to allow a larger number of people to fight in one match.

Classes or Full Programs, and Language?

Personally, I think this would be easiest to do as a Java KOTH with classes. It will run quick(-er than several other methods) and I could give entrants access to a variety of methods that give information about the stage.


Literally no work has been done yet.


Golf all the 16 logic gates with 2 inputs and 1 output!

This question asked for 16 independent functions. I would like the opposite: a single function that takes an additional parameter that specifies which of the 16 logic gates is required using an integer from 0 to 15. If you don't want to use a 0-based index of the list in the linked question then you should specify which integers map to which logic gate (but they should still be 0 to 15).


 0,0,0  falsey
 1,0,1  falsey
 2,1,0  truthy
 3,1,1  truthy
 4,1,1  falsey
 5,0,1  truthy
 6,1,0  truthy
 7,0,0  falsey
 8,0,0  truthy
 9,0,1  falsey
10,1,0  truthy
11,1,1  truthy
12,1,1  falsey
13,0,1  truthy
14,1,0  truthy
15,0,0  truthy

This is , so the shortest answer in bytes wins.

  • \$\begingroup\$ Here you go \$\endgroup\$ Commented Jun 15, 2016 at 10:37
  • 2
    \$\begingroup\$ @PeterTaylor That one is a kolmogorov-complexity. \$\endgroup\$
    – Leaky Nun
    Commented Jun 15, 2016 at 10:47
  • \$\begingroup\$ @Mego How is generating 0101010101010101\n0011001100110011\n0000111100001111\n0000000011111111 the same as golfing 16 logic gates? \$\endgroup\$
    – Leaky Nun
    Commented Jun 21, 2016 at 9:48
  • \$\begingroup\$ You may want to ban builtins. J has a two-byte solution, b. \$\endgroup\$ Commented Jun 25, 2016 at 22:18
  • \$\begingroup\$ @CᴏɴᴏʀO'Bʀɪᴇɴ How do I go about looking up what b. means? \$\endgroup\$
    – Neil
    Commented Jun 25, 2016 at 23:53
  • \$\begingroup\$ @Neil Voila \$\endgroup\$ Commented Jun 25, 2016 at 23:54
  • \$\begingroup\$ @CᴏɴᴏʀO'Bʀɪᴇɴ Thanks, I can see that excluding builtins will be necessary. (Strictly speaking, I asked how to look it up, rather than for a direct link, which wouldn't help me look up any other J code should I need to for any reason.) \$\endgroup\$
    – Neil
    Commented Jun 26, 2016 at 0:03
  • 1
    \$\begingroup\$ @Neil J is a hard language reverse. I would postix your search on google with site:jsoftware.com \$\endgroup\$ Commented Jun 26, 2016 at 0:05
7 8
10 11

You must log in to answer this question.

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