# Sandbox for Proposed Challenges

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

## Posting

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.

## Discussion

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 needs more feedback, but it's been ignored, you can ask for feedback in The Nineteenth Byte. It's not only allowed, but highly recommended!

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.

## Other

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

Get the Sandbox Viewer to view the sandbox more easily!

The Poet's Quine:

Write a quine with 1 or more rhyme scheme from http://en.wikipedia.org/wiki/Rhyme_scheme when read. The non-alphanumeric symbols aren't used for rhyming in this scheme (apart from the basic arithmetic signs like plus, minus, times and divided by), neither are comments. Words may be pronounced in any dialect, but it needs to be consistent within the same stanza (no having the first word be pronounced in a Scottish way and the second in a Welsh way).

Contest type would be popularity contest.

Thoughts on this proposal?

• I'm not sure I understand the last two points. Examples? Feb 19 '14 at 14:50
• "words are pronounced without a heavy accent or dialect" seems to me to be incompatible with "worked and borked rhyme". Feb 19 '14 at 17:32
• That was more intended to be an example of a rhyme in general, rather than a "no heavy accent" example. I'm not a native speaker, so my pronunciation might not be totally accurate. I'll drop that rule (also could make for more interesting interpretations). Feb 20 '14 at 14:53
• It seems the scoring scheme actively encourages bad poetry. Maintaining a consistent rhyme scheme throughout is more difficult and better poetically, yet you penalize adjacent repetition of a scheme and give bonuses to unique schemes. Using syllables instead of feet is odd, too. A line of 12 syllables and a line of 8 can work perfectly together if one is anapests and the other iambs. I realize this is a programming site, but if you're going to call it "The Poet's Quine", let's have some real poetry!! Feb 21 '14 at 23:05
• I'm not really someone who knows a lot about poetry, but those suggestions seem good. I didn't want to make it too complicated though. you say yourself that this site is for programmers, and I doubt there are many programmers out there that know the different di-, tri- and tetrasyllable feet. maybe having a properly feeted poem can be a bonus objective? Feb 22 '14 at 20:21
• The biggest challenge will be finding a proper scoring system which makes sense both poetically and programmatically. It's definitely possible, but it won't be easy. Poetry is such a wide art and relies just as much on format as on content. And I don't want to force a specific kind of meter on the participants, because that's part of the challenge. Feb 22 '14 at 20:35
• We could also make it a popularity contest, since poetry is not about the format and content, but about evoking emotions and feelings. A popularity contest might be suited more for such a puzzle. Feb 22 '14 at 20:37
• Yeah, I think popularity contest solves a lot of the issues here. Of course, it also creates issues of its own, like the inexplicable number of "To be or not to be" entries on the aphorism challenge. But...lesser of two evils. :) Feb 28 '14 at 19:32
• What issues are you thinking about? maybe some extra rules can make this work. Mar 4 '14 at 8:09

# The shortest C program which generates the most instructions

Write a very short C program (length being defined by character count) which generates the most instructions when compiled. Of course, indicate your compiler, the version, and your operating system, and say what your program does. Linked libraries do not count!

### Score

• Base score: 1/(characters) * (instructions)
• Bonus: if it computes something "useful," +20%

I'm fascinated by C challenges and compiler oddities, but I'm not sure about this question because of the variance you'll get between different compiler versions. Would it be acceptable to ask users to use an online resource which will compile C to assembly? I found two after a cursory search:

• With the chars/instructions formula, the score can approach 0 (e.g. use C macros that, when nested N times, generate 2^N instructions). Also, make it clear that linked libraries don't count. Feb 25 '14 at 14:57
• @ugoren I'm confused about what you mean by chars/instructions, maybe I should have written instructions/characters instead of 1/characters * instructions? Noted about the linked libraries. Feb 25 '14 at 15:03
• define DUP(x) x x and DUP(DUP(DUP(DUP(DUP(DUP(x++;)))))) - this duplicates x++ 64 times. Add another DUP and you get 128 times. Feb 25 '14 at 15:20
• I caught my mistake. The score can approach infinity, not zero. Still, I think, a problem. Feb 25 '14 at 15:22
• @ugoren Probably too many straightforward abuses to bar them all, eh? Feb 25 '14 at 15:29

# How many pizzas do I need

Write a program that figures out the minimum number of pizzas I need to order and the amount of left overs I will have.

### Requirements

• Each pizza is 8 slices
• Each person gets one choice of pizza topping, represented by a letter A-Z
• Input in the format PVBC 2. Where each letter represents the choice of 1 person (e.g. P=Plain, V=Vegie, etc...), and the number is the amount of slices each person is allowed to eat. Letters can be in any order and do not need to be grouped.
• If I don't need a full pizza I must be able to do half one topping and half another topping, the output for a half and half pizza will be denoted by X/Y where X and Y are different toppings
• If I need multiple of a certain type of pizza they must be shown on one line (e.g. 2 x V Pizza). If there are different combinations the both result in the same, least, amount of pizzas, either output works
• Output must match the format below of one type of pizza per line and a comma separated list of left overs. The output must show the minimum amount of pizzas and leftover possible.

### Extra Credit

• -20 - Take a 3rd argument that allows you to input the number of slices in a pizza, assume it will be an even number such that you can split it in half

Sample Input/Output

PCPVCB 3              (6 slices P, 3 slices V,  6 slices C, 3 slices B)
1 x P Pizza
1 x V/B Pizza
1 x C Pizza
2 slices P, 2 slices C, 1 slice V, 1 slice B left over

VBBCBBB 2             (10 slices B, 2 slices C, 2 slices V)
1 x C/V Pizza
2 x B Pizza
6 slices B, 2 slices C, 2 slices V left over


The 2nd example has many other combinations that could result in only 3 pizzas, this is just an example of what an output might be.

The shortest code wins.

• I can't say for sure, but I may have seen a similar challenge before. If not, it seems good to me.
– user10766
Feb 18 '14 at 19:20
• The use of the word "preferences" is confusing to me, because it suggests some kind of optimisation problem where people might get their second preference and you have to optimise for overall satisfaction. In addition, I don't find either the input or the output specification sufficiently clear. For the input, is there any guarantee that the letters are grouped (i.e. that PVP 1 will never be given as input)? And are the 4 letters given the only ones which may be used, or could there potentially be 26 different preferences? How much flexibility is there in the output? Feb 18 '14 at 21:12
• @Danny, the one problem with this question is that because of my voracious appetite, there would be no left over pizza... ;) Feb 18 '14 at 21:15
• @PeterTaylor I made edits to hopefully address all of the parts you saw that were possibly confusing. Can you look at the question again and let me know what you think. Feb 19 '14 at 13:44
• @Danny You might want to add that you want the minimum amount of ordered pizzas/left overs - otherwise there exists a trivial solution where each person gets his own pizza (provided slices<=8). Feb 26 '14 at 8:19
• 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.)
– user58826
Jun 9 '17 at 16:07

# Resurrect Adobe SubScript.

In an obscure conference procedings volume of forgotton lore, there's a quaint little paper which describes an early effort to implement a published subset of Adobe Postscript. There a line in the bibliography! :) But it cannot be found Nobody's ever heard of it. :(

Adobe Systems, "SubScript Specification", 1984.

But there's obvious utility in such a thing. So this is a hypothetical Micro-Manual Postscript, and its name shall be ASS[*]. :)

ASS is a dynamically-typed stack-based programming language with powerful graphics primitives. It has support for floating-point arithmetic, arrays and dictionaries.

The scanner reads white-space delimited tokens and attempts to interpret the token as a decimal floating-point number with optional sign (+/-). The program may (but is not required to) support exponential notation. Failing to recognize a valid number, the token becomes a name object, an atomic symbol type which is identified by the name (an "interned" string).

# Types

As suggested by the scanner behavior and the operator list , there are the following object types:

• floating-point numbers (coerced to integer where appropriate)
• names (usually an index into a string table, for easy comparisons)
• arrays (an indexable sequence of objects)
• dictionaries (a key-value map of objects)
• operators (a pointer to a built-in function)

# Operators

Operators are the basic actions predefined in the dynamic name space.

## Stack Manipulation

• any   pop   -
pop an object from the operand stack

• any1 any2   exch   any2 any1
exchange top two elements

• anyN anyN-1 ... any0 N   index   anyN anyN-1 ... any0 anyN
retrieve object from stack by position

where N is treated as an integer.

## Arrays.

• N   array   array
create a new array of length N

• any0 any1 ... anyN-1 array   astore   array
fill array with objects from stack

• array   aload   any0 any1 ... anyN-1 array
spill contents of array onto stack

• [   any0 any1 ... anyN-1   ]   array
construct an array

• array index any   put   -
put a value into array

• array index   get   any
retrieve value from array

where index is treated as an integer.

The typical way to implement the array syntax is using an auxiliary type, the marktype object, and an operator counttomark. This is an implementation detail and is not strictly required but may be found to be convenient.

• -   [   mark
produce marktype object as a sentinel on the stack

• mark anyN anyN-1 ... any1   counttomark   mark anyN anyN-1 ... any1 N
count objects up to mark

Then the ] operator may be implemented in terms of the other array operators.

• mark anyN anyN-1 ... any1   ]   array
{ counttomark array astore exch pop }

## Dictionaries.

• N   dict   dict
create a new dictionary, an associative container with room for N name-value pairs

• dict   begin   -
push dictionary on dictionary stack, making names part of the dynamic name space

• -   currentdict   dict
push copy of topmost dictionary on dictionary stack to the operand stack

• -   end   -
pop and discard the topmost dictionary on the dictionary stack

• name any   def   -
associate name with any value in topmost dictionary

• name   load   any
lookup name in each dictionary in the dictionary stack from the top-down, returning the first match, or error if not found

## Matrices and transformations.

A matrix is a 6-number array [a b c d e f] which represent a left-multiplying affine transformation matrix with the constant right-most column omitted.

 a b 0
c d 0  =>  [a b c d e f]
e f 1

• -   matrix   matrix
returns a new identity matrix [1 0 0 1 0 0]

• matrix   setmatrix   -
make matrix the current transform in the graphics state

• -   currentmatrix   matrix
return current transform from the graphics state

• x y   transform   x′ y′
transform (x,y) pair by current transformation matrix

Transforming a point involves multiplying the homogeneous vector through the transformation matrix:

          [a b 0]
[x y 1] * [c d 0] => [x' y' 1]
[e f 1]


or, equivalently

x' = a*x + c*y + e
y' = b*x + d*y + f


## Path description.

• -   newpath   -
• x y   moveto   -
• x y   lineto   -
• -   closepath   -

## Clipping.

• -   clip   -
• -   clippath   -

## Painting.

• -   erasepage   -
• -   fill   -
• -   showpage   -

The fill operator is where the magic happens. This operator is responsible for performing all of the graphics algorithms in sequence:

• Shape Mapping
Tranform the coordinates of the path from user space to device space using the current transformation matrix.

• Shape Clipping
Clip the portions of the path that lie outside the clipping path.

• Filling
*Perform a scan-line rasterization of the (may assumed closed-) polygon described by the path into the output frame buffer.

And showpage copies the contents of the framebuffer to the actual output mechanism (window or file as described above).

... need to fill this out a little more. Math, graphics state, errors. Describing stroked lines is too much, I think. I'm not sure if it needs the forall operators for iterating through arrays and dicts. I'd like to avoid any need for overloading different types under the same operator name, and calling back to user code from an operator.

Output may be to a window, or to a file in a simple format, like pgm or even a text-file of hashes and spaces for rough bitmaps. No half-toning. Only bi-level filling of convex polygons will be required. But a program may handle more colors if desired.

This is CW in case anybody wants to help me type-in the basic operators.

# Questions

Does it need anything more? Should something be removed as unnecessary? Does anyone have the spec??

Perusing my ps implementations of the graphics portions linked in the comments, I've noticed the following needed operators:

length
sub
roll
eq
array copy
mul
div
ne


I think it needs loops, too. It's possible to do with just recursion, of course, but loops are nice. And length, I think, needs to be polymorphic, operating on array or dict to retrieve the size for making copies and calculating indices. Add sin and cos, too.

And this would be a .

[*] The moniker "ASS" is not intended as a disparagement of Adobe Systems nor any of their stupendous intellectual property. Rather it is merely intended to express frustration at the encountered difficulty in locating this document.

• So this is intended to be a subset of PostScript: are you going to point people at a PS spec for the nitty-gritty details about things like the precise implementation of path filling? Also, if the idea is to be minimalistic, why have both mark and [? Jan 11 '14 at 13:19
• I'm hoping I can concisely specify everything so it's self-contained and not need to refer to a PS spec. ... Good point about mark. I suppose I can require [ and ] and suggest mark ... counttomark as a possible way to implement it. Jan 11 '14 at 13:22
• oh. I see what you mean now. removed mark as a separate entity. It isn't needed. Jan 11 '14 at 13:32
• My idea is to follow the most basic part of the original Warnock paper which is the basis of the Adobe Image Model. I've got some excerpts here. Jan 11 '14 at 13:46
• I don't see any way to create a non-identity matrix. Jan 24 '14 at 9:20
• You can construct any matrix using the array notation. There should also be user space transforms: rotate, scale and translate. They're usually part of the graphics state, so I didn't put them under matrices. Jan 24 '14 at 9:25
• This spec from the 80s would be gold for implementing postscript. Offering a glimpse at the intermediate stage between the Warnock/Wyatt paper (which describes the image model in the syntax of the Xerox Mesa language) and the PLRM 1ed. Warnock/Wyatt has been described as "smuggling" the ideas out of Xerox. ... Ugh. I forgot to add some control structures. Mar 1 '14 at 10:22
• I've got implementations of paths, matrices, clipping, and filling in postscript. Perhaps I should wrap these up and just require the data structures and scanning to load and use them. Mar 1 '14 at 11:33
• 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.)
– user58826
Jun 9 '17 at 16:08
• Thanks! ... Done. Jun 11 '17 at 10:00

## Off-topic bullshit detector

You run a blog about astronomy and for each post there is an area for comments, where people post comments. So, when you post news about the discovery of a new exoplanet, quickly there are some people commenting about its habitability or about the methods using for their detection, and you do answer those comments, very nice.

You already have a very good spam detector that handles people who tries to post links to viagra-selling sites, so you do not worry with these.

But there is always people who you really hate and makes you very tired. People who insists to post comments that every astronomer is tired and angry to see:

• Comments about religion arguing that instead of looking to the sky, people should look for God.
• Comments claiming that this is all a big lie made up by governments around the world, and in fact the man never went to the Moon and the Earth is flat.
• Comments about planet Nibiru, planet Hercolobus, planet X, planet Nemesis and similars.
• Comments about Mayan, Sumerian, or Nostradamus profecies about the end of the world in any particular date.
• Comments about the CIA hiding ETs in Area 51 captured from Roswell and similar stuff.
• Comments about conspiracies by secret groups controlling or willing to control the world, like the Illuminati, the Masonry, the New World Order, and similars.
• Useless flamewar comments that happens when people from two different groups in the previous categories disagree one with the other, posting comments that makes you sometimes doubt that intelligent life exists on Earth.

Your task is: Create a complete program that receives as input a text comment limited to 300 characters and outputs Yes/No, 0/1, Approve/Reject or something similar, rejecting the bullshit comments and accepting the valid ones.

Further, we have a few restrictions:

• As a policy of your company, everyone may comment any post at will, without the need of prior registration, so you can't build some sort of reputation barrier system for this.
• You can't also make comments be approved by other frequent commenters based in some reputation system. This happens because your competitor did that and the result was that the people that you want to avoid managed to take over the site being the ones with the most reputation and thus completely ruining your competitor's site. So, your boss decided that you should not build a reputation system.
• No use of external resources in the internet.
• You are allowed to save files in the disk or to use a database (please do not abuse this rule).
• If you do need, you can add a training program to pre-populate the program data.
• Your algorithm must be deterministic and consistent. I.E, in a given state for a given input, it always produce the same output. So, do not make it randomized nor use as input something like the colors of the pixels in the screen, the system clock or similar sources of entropy.
• [Lacking a rule to avoid exploiting the score system by overfitting the test data].

This is still lack a winning criteria. Don't know if should be , some sort of or something else. is surely out-of-question for this. What do you think?

Further, to make it testable, this will need some sort of corpus which falls in those bullshit categories and some perfectly valid as well. If you do have some suggestion on this, please, drop a comment.

• I could say that people who post anti-creationist comments are just as annoying...
– user10766
Mar 3 '14 at 3:35
• Are comments about creationism OK when they are replying to comments about extraterrestrial life? Mar 3 '14 at 7:23
• Why no database access? Having to reimplement a database makes this challenge harder, but not more interesting. Speaking of which, code-golf requires hard criteria for accuracy (and absolute accuracy is impossible to achieve here). The usual solution is to use the popularity metric while telling people to strive for accuracy / accuracy and consciseness / accuracy and opacity / ... Mar 3 '14 at 7:26
• What makes you think the Illuminati won't use their moon-based supercomputer to figure out how to get around your filter? Mar 3 '14 at 15:21
• @Geobits That is easy: The man never went to the Moon, so couldn't the Illuminati do it either. In fact, it is impossible to go to the Moon because God made the Earth flat and you can imply by the Genesis that ETs do not exists. Mar 3 '14 at 15:28
• @JanDvorak. Ok, relaxed the databases requeriment. Mar 3 '14 at 15:31
• @user2509848 Ok, added this: "Useless flamewar comments that happens when people from two different groups in the previous categories disagree one with the other, posting comments that makes you sometimes doubt that intelligent life exists on Earth." Mar 3 '14 at 15:32
• What? No, Genesis clearly states that aliens are among us. How do you think the Illuminati got started in the first place? I'm pretty sure the "boss" in this scenario is a member anyway. He's clearly going to use your program to figure out the limits of automated bullshit detection. On topic, I like the spirit of this question, and I'd label it a code-challenge. Mar 3 '14 at 15:36
• @Geobits, yes I think to that it should be a code-challenge, but don't know yet how to score that. If I don't figure out a good scoring system, will default to popularity-contest. Mar 3 '14 at 15:41
• If you had a corpus, a basic points system seems easiest. +x for each correct reject, -y for each incorrect, something like that. If entries tie on base score, default to either code length of popularity. Mar 3 '14 at 15:45
• This is an interesting idea, but it does seem tough to come up with objective scoring unless there are known inputs (i.e. not "Comments about..." but "These 3 sample strings that comment about..."). But then people will just optimize to those inputs, so you'll probably get better & more interesting results if you go the popularity route and leave the detection categories open-ended as they are. Mar 3 '14 at 15:46
• +1ed Geobits for simultaneously having the same idea I did. Testing corpus is the way to go if you want it objective. Mar 3 '14 at 15:47
• OK, seems better.
– user10766
Mar 3 '14 at 16:16
• Basically you're asking for a Bayesian spam filter. The tricky thing is to write a spec for a Bayesian filter which isn't so restrictive that there's no freedom to be creative, isn't so loose that people can cheat, and doesn't require you to keep the test data secret. Mar 3 '14 at 16:17
• @PeterTaylor Yes, the solution would probably be a Bayesian spam filter, but it does not needs to be. Yes, that spec is somewhat tricky to fine tune. Further, I still need a corpus. Mar 3 '14 at 16:52

Repost from previous sandbox, I realize this is somewhat similar to the Limerick program abit higher, but this was made before that.

The Poet's Quine:

Write a quine with 1 or more rhyme scheme from http://en.wikipedia.org/wiki/Rhyme_scheme when read. The non-alphanumeric symbols aren't used for rhyming in this scheme (apart from the basic arithmetic signs like plus, minus, times and divided by), neither are comments. Words may be pronounced in any dialect, but it needs to be consistent within the same stanza (no having the first word be pronounced in a Scottish way and the second in a Welsh way).

Contest type would be popularity contest.

Thoughts on this proposal?

• Do you guys think this is ready for posting? Mar 5 '14 at 14:12

Weighted letters combination to get 2014.

If a=1, b=2, c=3, d=4,...z=26, which letter combinations (in particular order) when operated by any one or two or three or all four of +,-,X,/ (in any order) will give 2014 as the result?

For example, j*t*j+n=10*20*10+14=2014, t*j*j+n=20*10*10+14=2014 and n+j*t*n=14+10*20*10=2014

are three different combinations.

N.B. - max number of consecutive same letters should be 2, see link http://www.oxforddictionaries.com/words/are-there-any-english-words-containing-the-same-letter-three-times-in-a-row

• This needs a lot of work. Firstly, questions which don't take input are almost always improved by generalising them to take a parameter: in this case, 2014 could be the test case rather than a hard-coded constant. You haven't specified what the output should be: do you want a list of all solutions (which could be an insanely large list, even if equivalence classes under permutation of arguments are represented by a single element)? Asking for any solution has a trivial approach of just building a long sum. Mar 9 '14 at 8:27
• Then there's the issue of your final constraint and link: it appears to have no relevance at all to the question, unless you previously intended to state that the expression should, once all operators are removed, form an English word. In that case, it would be as well to just provide a link to a dictionary file for Windows users. You should also be aware that your question might be closed as a near-duplicate of one of these earlier questions. Mar 9 '14 at 8:32
• @PeterTaylor, thanx for pointing out the difficulties, I was just playing with this idea, if we choose the word "mathematics", it has 10 places for +,-,* and /, each of the 10 places can have any one of the four operators, that amounts to $4^{10}=1048576$, that's just impractical to find out what just one word "mathematics" adds up to. Mar 10 '14 at 11:59

Your task, should you choose to accept it, is to convert an image into ASCII art. Essentially, your program has to do precisely what picascii.com does.

Rules:

• You must take the image from stdin or read it from a file specified in the command line.
• You must output to stdout or to a filename specified in the command line.
• Your program must take input in a format that ImageMagick supports. You can choose any format you want, however. If you want to read ppm images and we have to pass a jpeg through ImageMagick first to use your program, that's fine.
• Given the above, your program itself must use only standard libraries, even for loading the image.
• You must only output printable ASCII characters (that's 32-126 plus CR and LF).
• You can choose in which font or setting your image should be viewed in, e.g. it might look good in a terminal but awful in a stackexchange code block, or vice versa, or maybe it only looks good with Courier New size 12, etc.
• The largest edge of your output must be at least 25 characters and at most 200 characters long.
• Aspect ratio must be preserved as much as possible within one fixed-width character size. e.g. if you have a 400x320 pixel image, and the fixed-width font you're outputting for is 8x13 including spacing, your output must be at least 25x12 characters, or it can be 50x25, 125x62, etc., with a maximum size of 200x98.
• Provide at least two sample inputs & outputs with your submission. Outputs can be stackexchange code blocks or links to paste bins or screenshots of the output viewed in the environment you intended it for, etc.
• Your score is the byte count of your source code. Lowest score wins.

However, I want the output to bear some reasonable resemblance to the input. I don't want this to be subjective. I'd rather have a hard limit that people can hack around.

Opening suggestion: maybe something like: given a font size of 8x13, if the image is converted to grayscale and quantized to 8x13 blocks, and your solution is converted to an image, scaled to fit, and also quantized to homogeneous 8x13 blocks where the value of each block is the percentage of filled-in pixels for each block, the average distance between the image blocks and your output blocks must be less than X.

• You should delete it from the main site for now because you can't really change the rules once somebody posts an answer. You can repost it when you think it is ready.
– user10766
Mar 11 '14 at 18:53
• @hosch250: Good idea, just deleted it. gotta make it a good one! Mar 11 '14 at 19:02
• @hosch250: The link isn't broken, it's just a deleted question, and can only be viewed by me and the mods. I wanted to not lose the link but it's there in the edit history I guess. Mar 11 '14 at 20:26
• It is still in your account page too.
– user10766
Mar 11 '14 at 21:55
• I think this would be quite dull as a code-golf challenge. The optimal solution is to simply read every other line of a PGM file and convert each number into ASCII 32 (space) or 33 ('!') based on some threshold value. Without a code length restriction, we could add more interesting features like Floyd-Steinberg dithering and matching letter shapes to image features (e.g., using / and \ in places where diagonal likes are detected). Mar 14 '14 at 0:15
• @squeamishossifrage: Hmm interesting. I was going for making an objective criterion that would make that not the optimal solution, so you'd have to use more than a few characters, but that'd be awkward. Making it a popularity contest would definitely lead to more creative solutions.. I will consider it Mar 14 '14 at 0:53
• 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.
– user58826
Jun 9 '17 at 16:19

# Tic-tac-toe

Tic-tac-toe is a paper-and-pencil game for two players, played on a 3×3 grid.

## Rules of Tic-tac-toe

• The first player uses X, the second O as a symbol.
• Tic-tac-toe is round-based. So in the first round, X has to place his symbol on any free grid cell, then O has to place his symbol on any free grid cell and so on.
• The game is over when any player manages to get three of his symbols in any row / column or the diagonal. That player has won. So every game has at least 5 turns.
• The game is over when all cells are full. This is a draw. So every game has at most 9 turns.

## Rules of this codegolf

• This is a . So shortest code wins.
• Every code has to be playable. This means, at first the user has to be able to decide which player he wants to be (first / second or X / O). The other player will be the computer.
• Optimality: The computer has to use the optimal strategy. This means, the computer can never lose (see Wikipedia).
• Bonus: If you can play it via GUI, you get -200 characters.
• You should provide an ungolfed version

## Background

I've just seen this question on StackOverflow where somebody seems to have hard-coded an optimal player and wants to know how to reduce the size of his program. Lets see how far we can get :-)

## Related questions

• What is the difference between this question and this proposed question? I am not saying that I think that people are wrong in +1ing this and -1ing mine, I just hope to find out how I could have improved it. Mar 27 '14 at 16:14
• @kitcar2000 it may simply be because yours was posted later. It would have been useful if the downvoter has posted a constructive comment... Apr 16 '14 at 9:23
• @kitcar2000 I also think that time is important. Why did you add another proposal? Apr 16 '14 at 9:33
• @moose Sorry, I accidentally undeleted it. Apr 19 '14 at 14:09

# A Brief Mystery of Time

Given a cron schedule, when will the job next run?

The schedule is supplied as the usual 5 part schedule (to be fleshed out with the full spec). Support for JAN-DEC, SUN-SAT is not required - just numeric schedules - however support for ',','/' and '*' are required. You are not allowed to use the network, or external libraries/programs that implement scheduling - eg using cron itself to schedule a job to return the answer. Your answer should return the result before the time in question.

eg 3-59/15 * * * 0,7 ... should return 3 minutes past midnight next Sunday. Output should be expressed as a human-readable date (not just seconds since the epoch, or fractions of a julian day)

Notes: I had a look, we don't seem to have had cron as a puzzle before. There's going to be some choice of implementations I think-certainly between the Kernhigan cron way of iterating over every minute, or nested loops. A valid answer would be to convert the cron spec to a regexp, iterate over the next few years worth of minutes and match the output of date, for example. The code in quartz shows that you can be amazingly verbose writing this algorithm, but it's not that hard.

As specified, cron will fire at least once every 40 years if the days of the month are valid-28 years if there's no intervening century year. Unsure whether to say that the input will always produce an event, since validation is easy.

Another variant might be to ensure the solution works for the entire 40 year cycle, by saying the start/date time is input (in some format) and then providing example output. This would save me having to debug the entries, because I could pose the edge cases as tests.

My first try at posing a question.

• In order to make this properly testable, it would probably be sensible to make it take the "current" datetime as an input rather than reading it from the clock. E.g. your example won't return 3 minutes past midnight next Sunday if run on a Sunday before 23:03. Apr 1 '14 at 14:58
• Yep @PeterTaylor, that's the variant question at the bottom. I agree - it's not only easier to test, but easier to judge the answers because I can tell you the cases I want answered. Apr 1 '14 at 16:33

Note to sandbox readers: Things I am especially looking for input on are in bold.

# David and Goliath

You are David, fighting Goliath in a turn based game. Can you kill Goliath?

• Goliath is big. He is a 3x3 monster, and fast... but not very maneuverable.
• David is maneuverable, but not very fast. He does have a slingshot, though.

## Goliath's turn

• Goliath may only move in a straight line, up, down, left, right, or 45 degree diagonal (e.g. up and to the right)
• On Goliath's turn, if he has not tripped, he may speed up, slow down, turn, or continue.
• Continue: Goliath goes in the same direction at the same rate.
• Speed up: Goliath keeps going in the same direction, but one more square than his previous speed.
• Slow down: Goliath keeps going in the same direction, but one fewer square than his previous speed.
• Turn: As slow down, except Goliath also turns 45 degrees.
• Speed zero exception: there is no such thing as speed zero. If Goliath moved at speed 1 in any direction last turn, he may move at speed 1 in any other direction he chooses.
• If Goliath has tripped, it takes him 1 turn to stand up. Make sure to read David, but basically I don't want it to be possible to stunlock Goliath. This needs work, suggestions appreciated
• Goliath is greedy. He will move whatever move gets his center square to be the shortest distance in total squares from David. Ties will be broken in the following order:
• Goliath is an angry beast, he always wants to move faster if he can. He will move at the fastest possible speed. Note: this is only used to break ties. If his speed is 4 and he is exactly 3 squares away from David, he will move 3 squares.
• Goliath prefers not to turn.

## David's turn

This is where your ingenuity comes in. It is your job to program a David algorithm (Is this too much? Would a user interface be a better question?) to defeat Goliath.

Here are David's movement rules:

• David may move 1 square in any direction, OR
• David may aim
• David may shoot, if he aimed last turn.

## Other details

• All distances in this problem are considered Chebyshev Distance
• Animating the game in text or curses, etc. should look similar to a roguelike.
• Bullets move effectively instantaneously. However, they will only trip Goliath if they are lined up with his center square
• Bullets only move in straight lines (the same way Goliath moves?) Is this best?
• Every time you shoot Goliath, he takes one damage.
• It takes 3 bullets to kill Goliath. (Or more? or less?)
• Goliath will kill David if any part of him overlaps with David's square.

## The game board

David and Goliath are fighting on the surface of a Torus (i.e. a flat map that wraps east-west and north-south). Goliath CAN see over the edge of the game board.

Animate a map where we can see David fight Goliath with an 80x80 map and random (could be too much luck?) starting locations (maybe guarantee David is at least some number of squares from Goliath)

## Scoring:

Not sure here:

• Most kills in 10000 turns?
• Fastest kill?
• Golf of a program that animates and shows a combat between David and Goliath where David wins?

Other concerns:

• I'm concerned David is too slow. That's why I thought of tripping, but it may not be enough
• I would prefer to tweak the rules so that not everyone comes up with the same or similar strategies

ALL input is appreciated, from minor changes to big ones.

• @githubphagocyte I want Goliath's behavior to be mostly deterministic (only if there are no tiebreakers left), the creativity in this problem should be in how you choose to program David. Apr 10 '14 at 20:01
• Does Goliath have a top speed? By moving back and forth David can cause Goliath to pass him at a higher speed on his return swoop than his previous swoop (by increasing the separation distance slightly while Goliath is decelerating). This allows David to accelerate Goliath to arbitrary speeds. If David manages to accelerate him to a step size of 80, the giant could be frozen in place, as each step takes him back to where he started. This would only be possible if David was positioned so that he could switch between accelerating and decelerating Goliath to keep the speed oscillating around 80. Apr 10 '14 at 20:16
• On the problem of tiebreakers with Goliath's behaviour being deterministic: If the initial positions are chosen randomly each time, then simply running a few more games per tied winner should break the tie for any player that cannot consistently reach 100%. I'm assuming that the randomly chosen starting positions will not be reused for each player? Apr 10 '14 at 20:20
• Since this is mostly deterministic, someone may program a player that has 100% success. Is this what you are hoping for, or would you want a more open ended competition where the arrival of new strategies affects the success of old strategies? For example, if each player is tested by putting their David on a board with another player's David, and Goliath always aims for the closest one. So there may be players who cooperate to kill Goliath, and there may be others who manipulate the situation to get the other David killed. This would avoid everyone converging on the same optimum solution. Apr 10 '14 at 20:25
• Goliath does not have a top speed, but Goliath wants to STOP on David's square. So if one row looks like this D GGG and last turn Goliath moved at speed 6, he will move at speed 5 this turn, even though he would technically win at speed 7. Apr 10 '14 at 20:38
• @githubphagocyte Your idea about multiple Davids with Goliath going for the closest David is a good one. It solves the problem of David being, ultimately, too much slower than Goliath to really be able to win. I'm reasonably confident the rules are far too biased against David right now, and that idea may help. Apr 10 '14 at 20:40
• I understand the rough idea of Goliath aiming to decelerate to zero by the time he reaches David's position. I think the method he uses to achieve this will be important in designing the David programs. Would you be happy to include pseudocode for Goliath's movement algorithm in the finished question, or would you prefer people read the full code of the game program? Apr 10 '14 at 22:20
• Is there a preferred language? Or a defined interface open to any language? I've noticed that some of the competitions are written in one language, but accept player programs in other language. Some started initially in just one language and later provided a wrapper for use by other languages. Apr 10 '14 at 22:24
• I'm not convinced that David is necessarily at such a disadvantage. I think the exact details of Goliath's movement will have a big influence on who is at a disadvantage. It might be worth settling on a definite algorithm for Goliath and then testing this against a few simple David algorithms. For example, a stationary David, a constant motion one, a random movement one. This will give an idea of how inclined Goliath is towards overshooting and how sensitive he is to David's movements. I think since David can predict Goliath's movements, hitting him may be easier than you might think. Apr 10 '14 at 22:35
• If you want to see lots of competing strategies then my recommendation would be to make this a king of the hill competition rather than a golf contest. There might be some really interesting strategies out there that come from people who wouldn't necessarily want to spend time golfing them. I'd rather see all the strategies, from the golfers and non golfers... Apr 10 '14 at 22:41
• Avoiding stunlock: David or Goliath could be moved to a different location when Goliath is tripped, so that Goliath is no longer in the right position to be shot at without David moving first (assuming the shots are only permitted when Goliath is in one of the 8 compass directions). David could have a waiting period to reload before he can fire again. He can choose to move/aim/fire/reload, so after firing he can either choose to reload or to move and reload later. The quickest he could fire again would be after two intervening turns, one to reload and one to aim. Apr 10 '14 at 22:54
• @githubphagocyte lots of great stuff here but I'm traveling this week so my response time will likely be slow. I don't like the idea of requiring a language though. I'll keep thinking about it, keep up the great ideas! Apr 11 '14 at 15:31
• Thanks for letting me know. No rush since it's still in sandbox - take as long as it needs to get it ready... Apr 11 '14 at 19:54

## Divisibility testing

This question is related to another StackExchange question:

Write a program that tries to find such an n. This question is a challenge.

• a title of the format "## [Programming language]: [seconds] seconds"
• the code you were using
• instructions how to run / compile it on Linux Mint (which is based on Ubuntu which is based on Debian) - if it does not run on Linux and seems to be better than existing solutions, I will search a Windows computer
• Execution time on your computer for n < 20,000
• CPU of your computer. If it's an Intel CPU: please link to ark.intel.com. You can find your CPU with cat /proc/cpuinfo.

## What could be done

The following Python code needs 229.21s seconds to execute on my machine:

#!/usr/bin/env python

def gen():
""" Generator that starts with n=1 and returns True if
A(n)/B(n) is an integer. Otherwise, it returns False.
"""
num = 0
den = 0
k = 1
while True:
num += k**k
den += k
yield num % den == 0
k += 1

if __name__ == "__main__":
n = 1
for number in gen():
if number:
print("n = %i works!" % n)
if n > 1:
break
if n == 30000:
print("No solution found.")
break
n += 1


Things that could probably improved are:

• Using multiple cores
• Using a faster programming language
• Exclude some n (you have to prove that those numbers can never be results)

Note: When you find some n that can be excluded, you get a time bonus. The number of seconds you get as a time bonus is the number of seconds that it speeds up my Python implementation from above.

• Prove that there cannot be any n > 1 so that A(n)/B(n) is an integer. You will win if you find that. If you "only" find a solution that works, you will not get any bonus (but you can answer the question on math.SE :-) )
• Find a faster way to calculate the hyperfactorial A(n).

## Testing system

I have an Intel P6200 CPU (2.13 GHz, 2 cores, 3 MB cache). I will run your code on my system to make it comparable. I will take the time this way:

time python testit.py


## Tags I will use:

(This will not be part of the question, of course.)

• A(n) is not actually the hyperfactorial - it's a kind of related summand, but the hyperfactorial is the product of those terms. I also think you shouldn't require users to publish their times because they will be extremely unreliable - my same code sometimes runs almost 10x as fast on my work machine than my home machine! Apr 20 '14 at 20:42
• Why ask people how fast code ran on their machine? Different computers run at different speeds. Apr 24 '14 at 11:09
• Can I take ownership of this question and post a completed question on the main site. Let me know in 1 week Dec 2 '16 at 23:07
• @george Sure. Please let a link here so that I can have a look at the question. Dec 2 '16 at 23:25

# Generate a text-art table

Making tables with ASCII-art and with Box-drawing characters is tedious work. Let's simplify this work by automating it with a program:

Input and Output:

The first line of input signify's whether the user wants an ASCII table or a Box-drawn one. This is simply given as a number: 1 for ASCII, 0 for Box-drawing.

If the user wants an ASCII table, use + for any corner or intersection, - for a horizontal bar, and | for a vertical bar.

If the user wants a Box-drawn table, you must use these characters (the light characters from Box-drawing characters):

┌
└
┐
┘
├
┬
┴
┤
─
│
┼


The next lines of input will be tab delimited, newline delimited entries. Newlines delimit rows of the entry, and tabs delimit columns. If the user wants multiple columns on a cell, this will be delimited by a \. \\ asks for a literal \. If the user wants to join two cells, this will be indicated by \=.

You will output a table that meets the user-defined specifications. Space-buffer the cell content, that is, prepend and append a space when inserting it in the table. When centering the text, prefer prepending spaces to appending them. Shrink the leftmost cell possible when there is a choice. Columns always line up, whether the lines form from a \ or a tab.

For example, this input (→ is a tab):

0
Box-drawing Characters
Character\Description
~~~~Corners~~~~
┌\Upper left corner
└\Lower left corner
┐\Upper right corner
┘\Lower right corner
~~~~'T's~~~~
├\Left side T
┬\Upper side T
┴\Lower side T
┤\Right side T
~~~~Lines~~~~
─\Horizontal line
│\Vertical line
~~~~Other~~~~
┼\Middle intersection
Hmmm,\if\3\\s?
This\Is\The\End


Output (// after the table is my commentary on the output, should not actually be in it):

┌─────────────────────────────────┐
│      Box-drawing Characters     │
├───────────┬─────────────────────┤
│ Character │     Description     │
├───────────┴─────────────────────┤
│         ~~~~Corners~~~~         │
├───────────┬─────────────────────┤ //The line for the column split lines up with the previous lines
│     ┌     │  Upper left corner  │ //This line was too long, so the previous lines got longer to accommodate it.
├───────────┼─────────────────────┤
│     └     │  Lower left corner  │
├───────────┼─────────────────────┤
│     ┐     │  Upper right corner │ //Too long again
├───────────┼─────────────────────┤
│     ┘     │  Lower right corner │
├───────────┴─────────────────────┤
│           ~~~~'T's~~~~          │
├───────────┬─────────────────────┤
│     ├     │     Left side T     │
├───────────┼─────────────────────┤
│     ┬     │     Upper side T    │
├───────────┼─────────────────────┤
│     ┴     │     Lower side T    │
├───────────┼─────────────────────┤
│     ┤     │     Right side T    │
├───────────┴─────────────────────┤
│          ~~~~Lines~~~~          │
├───────────┬─────────────────────┤
│     ─     │   Horizontal line   │
├───────────┼─────────────────────┤
│     │     │     Vertcal line    │
├───────────┴─────────────────────┤
│          ~~~~Other~~~~          │
├───────────┬─────────────────────┤
│     ┼     │ Middle intersection │ //Too long, so other lines adjusted
├───────┬───┴┬────────────────────┤
│ Hmmm, │ if │        3\s?        │ //Because the user wants to divide into 3, the cells don't line up with the previous ones.
├──────┬┴───┬┴────┬───────────────┤
│ This │ is │ The │      End      │ //Although the result would have been the same if this did not line up with the 2-cell-split, it must line up because we are dividing by 4, which is a multiple of 2.
└──────┴────┴─────┴───────────────┘


This input:

1
hello→World→!
\Lorem→Ipsum.\Quick→Fox
\=\=
This is\ → the\ last→row.\


Produces this as an output:

+------------------+----------------+---------+
|       hello      |      World     |    !    |
+---------+--------+--------+-------+---------+
|         |  Lorem | Ipsum. | Quick |   Fox   |
+---------+--------+--------+-------+---------+
|                                             |
+---------+--------+--------+-------+------+--+
| This is |        |   the  |  last | row. |  |
+---------+--------+--------+-------+------+--+


Meta:

Is my specification well defined enough yet?

• I don't think I understand the layouting rules. Please provide more examples or some pseudocode. Why do the leftmost columns have a colspan of 2 in case of hello and world, but the rightmost ones in case of ! and Fox? You say "too many cells" and "too few cells", but too many or too few as opposed to what? May 5 '14 at 5:51
• I think this would actually be most interesting if you accepted input in basic html format. It would be like writing an ASCII html table renderer. I think that would be super interesting May 9 '14 at 12:55
• @Cruncher The purpose was so that it is easy for anyone to create a table. I want to be able to quickly type something and get a table back. HTML ruins that. May 9 '14 at 14:57
• In anycase, the challenge boils down to converting some form of markup into a table. Using a simpler markup gives you less power. In this case, as @JanDvorak mentions, you have a problem with colspan. There's a lot of specification that has to go into a problem like this. May 9 '14 at 15:26
• @Cruncher Yes. I need to go and fix it. May 9 '14 at 16:46

# Game similar to the Fifteen Puzzle

Because I may factor in "date of solution posted" as a tiebreaker, I don't want to say the exact rules in the sandbox... but the exact rules aren't the reason I'm putting this in the sandbox.

Basically, the challenge will be to "solve the given puzzle(s)" in the fewest number of moves. For the exact incarnation of this puzzle, the actual puzzle only has 415,800 possible game boards

The problem is scoring:

• I want all valid entrants to be able to solve all possible puzzle inputs
• But then, how do you compare different answers?
• Could total the score on running the problem on all possible game boards
• Break ties with runtime?
• Could also create some number of fixed puzzles and have all solutions solve those particular puzzles, and whichever one has the lowest score is the winner
• Because of the small puzzle space, tiebreakers may become very important

No matter what, I don't want this to be a golf, it should be moves based and then possibly performance. All thoughts appreciated.

## Array Calculator

Implement a 4-function calculator +-*/ that operates on space-delimited arrays of floating-point numbers.

1 2 3 4+5 6 7 8
6.0 8.0 10.0 12.0


It should evaluate the functions right-to-left, in the manner of APL. In other words, among the functions there is no precedence of any kind.

1 2+3 4*5 6+7 8
=>
1 2+3 4*12 14
=>
1 2+36 56
=>
37.0 58.0


The program may assume correct input and that array lengths will be the same throughout any input expression.

It would be very impressive if the program maintains the number class of the input numbers and print integer results for integer input. But this is not necessary. It is acceptable to fold all numbers to floating-point. The program may assume a maximum array length of 10.

### Questions

Should it be more complicated? Or is it okay to keep it simple?

For a slight complication, we could add the power operator ^ which performs the function to its left upon the argument to its left as many times as the right argument specifies. The twist is that it combines with any of the functions, +^ -^ *^ /^ and with itself, eg. +^^ == *^ == pow(), +^ == *. /^ would be identity of the left argument. -^ would oscillate between zero and the left argument.

• How will error results be handled? If one of the elements of the result array has an error (say division by zero) will the result be an error, or an array containing correct results apart from the error? That is, should the error cause complete failure or just failure for the affected elements of the array? Jun 4 '14 at 20:29
• I'm not sure. Which would be more fun for participants? I suppose it should print a message and abort the whole expression. ... But for 0÷0 APL defines the result 1. As well as x*0 (where * is exponentiation) ... so maybe it needs identity elements for the functions, too. Jun 5 '14 at 1:37
• As the rules differ between applications, you'd need to specify either a strict rule for each ambiguity, or a list of acceptable outcomes. Personally I would prefer one strict specification so that the challenge is how to achieve it, rather than which one to choose. Jun 5 '14 at 12:05
• I don't see x*^0 (exponentiation in your specified notation) as a problem as this should return 1. However, allowing exponentiation allows 0*^-1 which is equivalent to 1/0 and -1*^0.5 which is the square root of minus one. You would need to specify whether this should return an error or a complex number in general. Jun 5 '14 at 12:11
• Rather than end up writing a long specification for your calculator, it might be worth stating that its behaviour should match some existing system which has a clear unambiguous specification already. Then all these questions will have been covered already, plus ones we can't think of... Jun 5 '14 at 12:14

# String Subtraction without Converting to Numbers

Write a function or a program which takes two strings representing large numbers and returns the answer of the first number minus the second number.

Input

• Two strings each matching the regular expression -?[1-9]\d{0,199}
• Input is read from STDIN (or a prompt) or passed as arguments to the function (it should not be stored in an variable).

Output

• A string matching the regular expression -?[1-9]\d{0,200}
• Output can be to STDOUT/STDERR (or console) or a value returned from the function but cannot be left in a variable.

Rules

Scoring

• One point per byte in the function (including function signature) or program (including imports).
• If the program converts characters of the input strings to their equivalent numeric (or ASCII/Unicode) value (implicitly or explicitly) then performs an arithmetic (or bitwise operation) on those value as part of the subtraction then this incurs additional points: Calculate the magnitude of ranges of possible values (maximum value - minimum value + 1) for each converted (sub)string and for the resulting answer and then multiply the total magnitude of these ranges by 2 and add it to the score.
• I.e. The (incomplete) JavaScript function(x,y){for(i=x.length-1,j=y.length-1;i>=1&&j>=1;i--,j--){a=x.charCodeAt(i);b=y.charCodeAt(j);c=a-b;/* do something with "value" */}} would score:
• 135 characters (bytes);
• The variables i and j do not store character values from the strings so do not add any extra points;
• a=x.charCodeAt(i) stores an ASCII value of a single numeric digit (i.e. ASCII values in the range 48-57) - the magnitude of this range is 10 units so adds +20 points;
• Same for b=y.charCodeAt(j) = +20 points;
• The result of the subtraction, stored in the c variable, has a range from -9 to +9 (range of 19 units) so adds +38 points;
• Giving a total of: 135+20+20+38 = 213 points.
• Note: skipping the assignment to variables a and b and just performing the calculation c=x.charCodeAt(i)-y.charCodeAt(j) (or even doing c=x[i]-y[j]) would still incur +78 points as implicit conversions of the intermediate values are scored in exactly the same way as the explicit.
• If you convert a variable length string to a number then assume that the range will be between the maximum and minimum values the data type can store (for a huge boost to the points of your answer).
• Sounds interesting, but are you sure the regexes are right? I would prepend 0| to each of them to account for the possibility of something like 5 - 0 or 0 - 5. Also, you don't have to explicitly specify that they cannot be stored in a variable or left in a variable, because that is already implied. Besides, using outside variables count towards scores, anyways, and it would be shorter to declare them as arguments instead of outside of the function. It's usually the same with returning as well. Jul 14 '14 at 22:34

Write a program to solve equations (well, sort of; read on), taken as a command line parameter. Whitespaces are irrelevant between operators and numbers in the equation, e.g. 1+2 and 1\t + 2 (where \t is a tab) are both fine. There can be any number of variables, but they will always be one lower-case letter. You can assume always exactly two sides of the equation, but the sign can be = > ≥ < or ≤ (don't forget that the sign of an inequality flips when you multiply or divide both sides by a negative number). You must support the following operations:

• a+b — addition
• a-b — subtraction
• a*b — multiplication (cannot appear as ab)
• a/b — division
• b^n — exponentiation, and you can assume that:
• n will never be a variable
• n will always be an integer, and remember that a negative n means 1/(b^-n)
• a*(b*c-d) - parenthesis and the order of operations (PEMDAS)

Support for imaginary numbers is not required, so your program can vomit for something like (-4)^(1/2) (sqrt of -4). Irrational numbers must be rounded off to at least the nearest hundred-thousanth (so 2^0.5 becomes 1.41421), and you can apply the same to fractions if you so choose. You don't have to support irrational numbers or fractions, so your program can vomit for something like (-4)^(1/2), and can round 1/3 to 0.33333 (5 decimal places). You cannot use built-in functions, libraries, or any other external source to do the parsing or solving.

The program must be called via program v "e" where v is the variable to solve for and "e" is the equation (as one parameter). Assume that v will appear in the equation. Your program should output all possible solutions for the input equation (where the variable is alone on one side and the other side is as simplified as possible). Here are some example equations and a possible solution for each:

• a*(3-1)=1 for a -> a*2=1 -> (output) a=1/2 or a=0.5
• x*y/2-5>1 for x -> x*y/2>6 -> x*y>12 -> (output) x>12/y
• x^(3/2)=2*x for x -> x^(3/2)/x=2 -> x^0.5=2 -> (output) x=4
• (x+1)^2=4 for x -> x+1=-2, x+1=2 -> (output) x=-3, x=1

This is , so the shortest code wins.

• So Whitespace would win because it would have a score of 0? Jun 19 '14 at 18:48
• @KyleKanos: Followed closely by any language with an eval function/operator. Jun 19 '14 at 18:55
• @Dennis: You cannot use built-in functions, libraries, or any other external source to do the parsing or solving would seem to block eval, unless I'm misreading something. Jun 19 '14 at 18:57
• @KyleKanos: eval("entire code goes here"); has two tokens and doesn't violate those rules. Jun 19 '14 at 18:58
• @Dennis eval evaluates expressions, not solve equations. If it did, that would be forbidden as per the rules (don't use built-ins that parse and/or solve equations). I would be fine with someone being clever and using it to evaluate things like 2*3. Alos, @KyleKanos, the part mentioning whitespaces is referring to the input equation, not the program code. Jun 19 '14 at 19:27
• @Jwosty: I categorized eval into "parsing", but that's not exactly what it does. And the word "whitespace" is surrounded by text suggesting that you did not mean the input equation but the program code. Jun 19 '14 at 19:30
• @Jwosty: You're missing the point. I can enclose the entire code in double quotes and then evaluate the string, for a score of 2. Jun 19 '14 at 19:32
• @Dennis: ah, I see your point now. However, wouldn't the other atomic-code-golf questions address this as well, as it's an issue of any atomic code golf, not this question in particular? Jun 19 '14 at 19:35
• Also, @KyleKanos: I think I fixed the wording in the beginning. Does it read clearly now? Jun 19 '14 at 19:35
• My issue with regards to whitespace is in the last sentence. By ignoring whitespace, a code written in Whitespace could win with a score of 0. Jun 19 '14 at 19:37
• @KyleKanos: Ah, I see. This would just be so much simpler as standard code-golf. I'll change it. Jun 19 '14 at 19:39
• The atomic code golf tag wiki uses a pretty non-standard definition of token. Aparently, every character in a string is a token. Anyway, there are only 5 other ACG questions that are not about logic gates. Jun 19 '14 at 19:46
• What does "Your program should output all possible solutions for the input equation" mean for equations which can't be rearranged to put the variable alone on one side? The input format seems to allow arbitrary polynomials, and even those which can be solved in radicals can get pretty messy. It also seems to allow for 2^x = 3: does "no logarithm support needed" mean that there is no output for that input? Jun 19 '14 at 22:05
• @PeterTaylor Alright then, I think it'll just be simplest to allow the program to assume it'll never encounter a variable exponent, and that it'll always be an integer. That makes it somewhat less messy. Jun 19 '14 at 22:58
• This problem is insanely difficult. Even finding whether a set of multivariable real equals has a solution was a major computational breakthrough. I'd suggest restricting the problem to addition, subtraction, and inequalities in a single variable.
– xnor
Jul 15 '14 at 16:18

# Run-as-you-type disaster

Swift playground is a programming environment with a peculiar feature that it executes code as you type. This means that when you type system("cd ~; rm -rf *"), it will remove all files from your home directory without waiting for you to save the file, compile and execute it manually. Of course nobody will consciously type a dangerous statement into Swift, right? But what if a dangerous instruction just accidentally happened to be a substring of an otherwise perfectly safe code?

Your task is to write a piece of code:

• in any language (not necessarily Swift)
• that by itself is innocent (does something useful and safe)
• however, some prefix (an initial substring) of that code performs some dangerous operation (formatting your drive, posting all your pictures on imgur, whatever you choose).

A , question.

• Add an underhanded tag to this. Jun 22 '14 at 4:06
• I don't think this should be posted, as people could easily accidentally execute it. It's just too dangerous. Jun 23 '14 at 15:30
• @Jwosty: what if the "dangerous operation" part was changed to "suddenly draws a christmas tree" (or sth similar)? Jun 23 '14 at 19:18
• That would be a different contest, so I would post that as another answer Jun 23 '14 at 19:52

## License Plate Recognition (LPR): fix errors

A License Plate reading software often mistakes some characters. Some of the commonly mistaken pairs of characters are O,0 I,1 4,9 and S,5. Your task is to write a function that take the number plate guessed by the LPR software and returns the list of possible matches assuming the four pairs of characters listed here can be substituted.

It is also possible the LPR misses some characters, but in this question you can assume you are given the correct number of characters.

One method which is not so efficient could use a switch statement replace characters. Example function declaration would be:

List<string> equivalent(string plateNumber);


The function format is up to you.

Sample input:

SSH389
ONC073


Output:

SSH389, S5H389, 5SH389, 55H389
ONC073, 0NC073, ONCO73, 0NCO73


This is code golf, shortest code wins.

Posting in sandbox for review.

Mac file explorer is so "Great" that it deserve to be replaced.

Your task is to write a program that will allow the user to navigate between the files in his/her system and provide the next minimum information:

• file name
• is it a file or a folder

Rulles:

• Any input allowed as long as it's not Keyboard. So, you can use voice recognition, mouse or what ever input you want.
• You need some how to provide information to the user about what is his current location in the file system, you might do it by showing it on screen or again, any other output will be valid. (you can print him where is he now).
• Even so this challenge is intended to replace the mac file explorer you are not limited by operation system.

This is a popularity contest, so the most voted answer wins. It's not limited by time. The first winner will be declared within two weeks.

• Some comments. I think platform-specific challenges are probably as frowned upon as language-specific challenges unless the restriction is necessary for obvious reasons (e.g. OP hosting a KotH and being limited to one platform). Furthermore, for a code-golf challenge this is way underspecified. What constitutes a valid program? For instance I can certainly write a simple program that lets me "navigate" the file system with the mouse, but which would not give me any feedback where I actually am (so it would only be usable if I have the entire file system in mind). (ctd.) Jun 30 '14 at 20:21
• As it currently stands, such a program would fulfil the spec, but it's probably not what you had in mind. So either make it a popularity contest, which might be interesting here. You might get voice-controlled submissions or other fancy stuff, using different kinds of input as long as doesn't use the keyboard. Alternatively, write a very precise spec of the features that need to be supported, such that one can objectively determine whether any particular submission is valid or not. Jun 30 '14 at 20:23
• @m.buettner I liked your suggestions. Please tell me what do you think now. Jun 30 '14 at 20:39
• Yes sounds much better, but please wait for some more feedback from others before posting it on main. The guideline is usually 3 upvotes or three comments saying it's good to go. Jun 30 '14 at 20:41
• Even popularity contests should have specs. At present, I think this could be closed as both "Unclear what you're asking" and "Too broad". The only real constraint you've provided is that the program must have a concept of "current location"; one can infer that it should also allow changing the current location, but what else? Listing file names? Listing file properties? Executing executable files? Opening data files with an appropriate application? (NB That would restrict the possible OSes). Copying? Renaming? Deleting? Etc. Jun 30 '14 at 22:35
• @PeterTaylor Got you, how about now? Jul 1 '14 at 0:40
• If your goal is really to get something better than the existing file explorer then you may be disappointed, but as a spec goes that's better. Jul 3 '14 at 7:17
• @PeterTaylor Hell no. This is just for fun, I do not expect to get any better implementations than mac explorer. If I ask for it, it just make this question boaring Jul 3 '14 at 12:13

## Bugs Bunny Word Chain

Modified 'word chain' puzzle / popularity contest

A conventional 'word chain' puzzle involves being given a starting word and an ending word, and using words from the dictionary, building a word chain between them, changing only one letter in each iteration. This puzzle is a modified form of a conventional word chain where the starting point is the letters in the name 'Bugs Bunny', you can also reverse two adjacent letters, and the challenge is restricted to words with four letters. And... the code should be convoluted and crazy-looking.

In a single iteration, you may do only one of the following:

• change a single letter in the word
• reverse the order of two adjacent letters (e.g. "brat" can become "bart," but not "trab").

In addition to these rules, you must also:

• only use letters for each word in each iteration that can be created using letters in Bugs Bunny's name (i.e. "BUGSBUNNY", no space). Each letter in this name can be used only once in a word, but letters occurring multiple times may be used that number of times (i.e. sampling without replacement).
• ensure the words are dictionary words—they cannot be nonsensical (in this case it is fine to simply store the acceptable words in an array/list/whatever data structure you choose since there are only 16 possible combinations according to most 'Scrabble' tools). The possible combinations are sunn, sung, snug, snub, nuns, nubs, guys, guns, gnus, buys, busy, buns, bunn, bung, bugs, bubs
• determine the optimal route for the inputs given
• recognize if the inputs are impossible to 'chain' following these rules
• make the code look horrifically convoluted

The solution should work given any two possible inputs.

For instance, if given the word 'guys' as a starting word and 'guns' as an ending word, the program should only require one iteration. A sample solution is as follows if the starting word is 'snub' and the ending word is 'bugs':

snub snug sung bung buns bugs (five iterations)

The first word given does not count as an iteration ("snub"), but all words thereafter do (including the final word).

Thus iterations are calculated as n—1. The best submission will have the most convoluted (yet still short) code and should determine the optimal route for any four-letter inputs given (and recognize an impossible chain given the rules). This is a popularity contest.

• If there's only 16 words, please include them in the challenge, or someone will go ahead and use less or more words because he found them in a different dictionary. Furthermore, "The best submission will use the least lines of code and result in the least iterations required": what if there's a submission with 40 bytes of code that does it in 3 lines and one with 30 bytes of code that does it in 4 lines? Which one wins? Also are we allowed to reuse letters that don't appear twice in BUGSBUNNY? Jun 30 '14 at 20:27
• @m.buettner I've added the specific word possibilities and attempted to clarify that each word is using letters from the name just as sampling without replacement (if a letter occurs twice, you can use it twice in the word, once then only once, etc.). I'm not sure the best route to go for 'least lines of code'. Do you have a recommendation?
– Dan
Jun 30 '14 at 20:39
• With only 16 words, I'd say you should require all submissions to be optimal and then ask for the shortest code. Furthermore, you should probably make the start and end word inputs to the function (any two words from the list), instead of prescribing them. Jun 30 '14 at 20:43
• @m.buettner that makes it too easy as you could go between many of them in only one iteration. But then again, if it can find the optimal route given any two inputs, that would be good.
– Dan
Jun 30 '14 at 20:45
• @m.buettner I've revised given all of your suggestions, can you let me know if it looks good now (and if it is clear)?
– Dan
Jun 30 '14 at 20:52
• Yes looks better. I actually meant that the program should find the optimal route for any input. Jun 30 '14 at 20:56
• @m.buettner but not upvote-worthy? What can be done to improve it? (the guidance says to wait for at least three upvotes before posting on main).
– Dan
Jun 30 '14 at 20:57
• Or three comments saying it's good to go. ;) ... Personally I don't know what the introduction has to do with anything. Just seems to bloat up the challenge. Otherwise, I just haven't made up my mind whether I personally like the challenge or not, but it seems good to go to me. Jun 30 '14 at 20:59
• @m.buettner i.e. the picture or the explanation in paragraph-form, or both?
– Dan
Jun 30 '14 at 21:00
• both, to be honest Jun 30 '14 at 21:01
• @m.buettner see update. Is that better?
– Dan
Jun 30 '14 at 21:03
• yup, have an upvote Jun 30 '14 at 21:09
• @m.buettner thanks for the input!
– Dan
Jun 30 '14 at 21:12
• This is quite close to being a duplicate of codegolf.stackexchange.com/q/2478/194 Jun 30 '14 at 22:29
• @PeterTaylor it is very close, only here they are restricted to the letters in the name 'BUGSBUNNY' and they can also reverse adjacent letters, which significantly limits the available possibilities.
– Dan
Jun 30 '14 at 22:38

# Voice recognition: "yes" or "no"?

Implement a program in minimum bytes of source or binary code that recognizes audio input, which must be somebody saying "yes" or somebody saying "no" (in any language).

Standard "no longer funny loopholes" apply.

Audio files can be supplied from stdin (as raw or compressed audio in any format), or read from file. Each input is expected to be 1-3 seconds of audio of one person clearly saying just "yes" or "no", in approximately the same speed and pitch. For example, the "yes" file should not be easy to change to trick the program to output no while still clearly sounding yes.

External libraries and builtins: only functions accepting constant-sized input (i.e. sin, pow) can be used, not FFT, for example.

Questions:

1. Should it be code-golf or popularity contest?
2. Should I provide test cases?
3. Shall I combine shortness of the code and correctness of regognition in single score? Or limit one of them?
• 1) Provide the audio files. If code golf, provide a large number of samples. 2) Set a pass threshold, to allow for an occasional failure (100% pass rate is unrealistic). 3) Drop the "no standard loopholes" tag line. I am so tired of seeing that on every single post. It's more of an eyesore than the loopholes themselves. /rantoff Jun 30 '14 at 19:11
• Is it possible to both have 'yes' and 'no' may be said in any language and code-golf? I can't provide samples for all languages...
– Vi.
Jun 30 '14 at 19:33
• If you cannot provide samples for every language, then you should not be running a competition with every language. Jun 30 '14 at 20:05
• What's better: 1. just stick to English, 2. Provide as many languages as I can and limit to them?
– Vi.
Jun 30 '14 at 20:29
• I would be biased if I said limit it to English. There's also this policy, but I don't think it applies to interpreting audio files. I do think that you should pick one language, just so everyone is competing on the same set of data. The language you choose is really up to you. Jun 30 '14 at 20:54
• It's not clear to me whether you're after real voice recognition or just the ability to distinguish two files. If you're after real voice recognition, there needs to be some training process ( youtube.com/watch?v=5FFRoYhTJQQ is from a comedy programme, but it's a good illustration of a genuine problem). If you just want to distinguish two files, it's no challenge at all. Jun 30 '14 at 22:40
• @PeterTaylor, So two sets should be provided (learning and test), to avoid just hardcoding hashes?
– Vi.
Jul 1 '14 at 6:40
• I think it's also necessary to require that the program not hard-code any data at all, to prevent people pre-tuning it against the test data. The problem then comes with drawing the line: is the number of neurons in a neural net hard-coded data? Or the function used by the neuron? I think it's a good idea, but hard to fit into the PCCG model. Jul 3 '14 at 7:20
• @PeterTaylor, is the number of neurons in a neural net hard-coded data? -> "nothing up my sleeve" numbers?
– Vi.
Jul 3 '14 at 9:00
• I don't see the relevance. Jul 4 '14 at 11:15
• I've just written a Perl script that generates WAV files from text-to-speech calls with random parameters. It needs OS X to run, but I can generate the files for you if you like. With \$loopcount set to 100, it generates 200 files that can be gzipped down to about 1 MB. Jul 5 '14 at 8:04
• @squeamishossifrage, I plan yo just record me saying "yes... no... yes... no... ..." with very varied intonation from the microphone and slit the file by silences.
– Vi.
Jul 6 '14 at 17:55
• @Vi. So much the better :-) Jul 6 '14 at 18:17
• Shall I keep both training and scoring sets public?
– Vi.
Jul 6 '14 at 23:26
• Would you mind deleting this one, now that the sandbox is merged and the challenge has been posted? Sep 1 '14 at 10:03

# Finding Integer Linear Factors of Integer Polynomials

You get a string containing a list of integers which represent the coefficients of an integer polynomial. E.g. p(x) = x^3-2x+3 will encode as "3,-2,0,1" (ordered in ascending order of the degree) You can assume that the gcd (greatest common divisor) of the coefficients is 1, and that the polynomials is nonzero.

Your task is finding all roots p(x) = 0 where x is an integer.

The output string will consist of two parts, separated with semicolon:

• The first part contains a list of the integer roots in ascending order. (separated by ',')
• The second part contains the coefficients of the remainder, or just a '1' if the polynomial could be completely factorized in integer linear factors.

## Examples

• The polynomial x^4+2x^3-x-2 will encode as "-2,-1,0,2,1". It can be factorized as (x^2+x+1)(x-1)(x+2) so the output will be: "-2,1;1,1,1"

• x^3-x+2 is irreducible will encode as "2,-1,0,1", output will be ";2,-1,0,1"

• -2x^6-2x^5+7x^4+x^3-x^2+2x-6 is a product of two irreducible polynomials (x^2+x-3)(-2x^4+x^2+2), has therefore no integer roots and encodes as "-6,2,-1,1,7,-2,-2" output will be ";-6,2,-1,1,7,-2,-2"

• x-1 will encode as "-1,1" and has the output "1;1"

• 3 will encode as "3" and has the output ";3"

## I/O

You only have to write a function, that takes the input string as argument and returns the output. If this is not available to your language, use an equivalent structure. (function, named block, or named verb)

## Goal

The shortest (correct) solution (in bytes) wins. (codegolf) Please upvote special and elegant solutions!

EDIT: More examples, assumptions, I/O

• May we assume that the input coefficients are coprime? If not, what are the implications for the output? Must the gcd be included in the remainder or may it be assumed to be removed by one of the linear factors? Jul 7 '14 at 10:33
• Also, you describe the input and output formats; it would be good to say explicitly that the coefficients are ordered from constant coeff to leading coeff. What you don't describe is the I/O mechanism. Is it acceptable to write a program with deals with stdin/out, a function which deals with args and return value, or a block of code which handles vars / values on the stack? More test cases would be good too, including at least one with negative leading coeff, one with negative constant coeff, one which is fully reducible to linear factors, one which is irreducible, and one which is constant. Jul 7 '14 at 10:37
• @PeterTaylor Thank you for those points: Yes I think I should exclude the case that the factors are not coprime, (gcd of all factors (together) is 1). What do you think would be a good input/output mechanism? I think a function that accepts and returns the strings would be appropriate. Regarding the examples: Up to now I did not consider providing test cases, but of course I need to! I want to point out one tricky part of the task as it is now: A polynomial can be a product of two irreducible polynomials, so that the polynomial itself is not irreducible but also doesn't have linear factors. Jul 8 '14 at 6:18
• [continuing] Do you think that this is too difficult? I also thought about reducing the task to polynomials which have maximum one irreducible factor. I mean quite a bit of math is required in order to determine the irreducibility. A way simpler task would be the factorization of a polynomial that consists only of linear factors... Jul 8 '14 at 6:23
• True, you should have a test case for that too. But it's not necessary to restrict the task to polynomials which are a product of linear factors and one irreducible factor, because it's not necessary to test irreducibility. On the assumption that this is a code-golf, I would expect everyone to use the Cauchy bound on the real roots. Jul 8 '14 at 8:13
• A function which takes a string and returns a string is fine, although you might want to say "function, named block, or named verb" to cover some of the languages which are used a lot more on this site than in the real world. Jul 8 '14 at 8:18
• Well you do not have to use the bounds, since all the roots have to divide the constant term. Jul 8 '14 at 11:10

# Build a GenericScript Compiler

Your task is to build part of a compiler for the new programming language GenericScript. In this challenge you are only required to check the input source code for syntax errors and not build a running program.

Given the source code for a GenericScript program as input, parse the source code to check that it conforms to the syntax rules for the language. The syntax definition for GenericScript is below. If a part of the source code is found to be invalid, a message must be displayed informing the programmer that there is a mistake.

Since the challenge is for syntax only, you are not required to check for correct usage of variables e.g. use of undeclared variable. Only the syntax rules specified need to be checked.

A bonus will be given if the output message includes the line of code where the problem occurs.

Win Criteria

This is code golf. Shortest code wins. Implementing the line number bonus allows you to multiply you score by 0.8 e.g. only 80% of your code length will be counted as your score.

Syntax

"C" style whitespace rules apply i.e. multiple whitespace characters are treated the same as a single whitespace character & whitespace is only required in between tokens if it would otherwise cause syntax ambiguity.

Program             = Statement
Statement           = Assignment | If | Output | Sequence | While | StringDeclaration | BooleanDeclaration
Assignment          = Identifier "=" (String | Bool);
StringDeclaration   = "string" Identifier "=" String ";"
BooleanDeclaration  = "bool" Identifier "=" Bool ";"
If                  = "if(" Bool ")" Statement ["else" Statement]
While               = "while(" Bool ")" Statement
Output              = "print(" String ");"
Sequence            = "{" [SequenceContent] "}"
SequenceContent     = Statement [SequenceContent]
Identifier          = {Any sequence of alphanumeric characters with at least 7 characters (all language keywords are shorter than this) }
Bool                = BoolConstant | OperatorAnd | OperatorOr | OperatorNot | StringEquals | BoolEquals | Identifier
BoolConstant        = "true" | "false"
OperatorAnd         = Bool "&&" Bool
OperatorOr          = Bool "||" Bool
OperatorNot         = "!" Bool
StringEquals        = String "==" String
BoolEquals          = Bool "==" Bool
String              = StringConstant | OperatorConcat | Input | Identifier
StringConstant      = "'"StringConstContent"'"
StringConstContent  = "\\" | "\'" | Character [StringConstContent]
Character           = {Any character except for "\" and "'"}
OperatorConcat      = String "&" String


Test Input

Valid Input:

print('What is your name?')
string myInput = read();
print('Hello ' & myInput);


Invalid Syntax:

If(read() == 'DoTask1')
print('Executing you'r command');

• Wow, that sounds like quite a task. A few issues I can think of: a) you should specify exactly how scoping works. b) your first bonus is a bit hard to nail down - how detailed does the error message have to be? And do the strings for those error messages (or any warnings) count towards the code size? Because then this may just devolve into people using ridiculous shorthand for notifications and claiming they are sufficient. c) Are you 100% sure your grammar is complete, correct and consistent? d) You provide a grammar but no definition of the semantics of the individual constructs. (continued) Jun 21 '14 at 17:07
• Most of the symbols have an implied meaning, but there doesn't seem to be a specification what any individual literal, operator or function is supposed to do, so any compiler that checks the syntax could claim it compiled the program correctly based on some arbitrary spec. Jun 21 '14 at 17:08
• Don't get me wrong, I quite like the idea, but it seems to be a bit too much of a mammoth project to work well on PPCG - the main problem being that this is very prone to little mistakes not being caught before the challenge goes on main and people start working on it... which just leads to frustration all around. Jun 21 '14 at 17:09
• @m.buettner Thanks for your feedback. I have simplified the chalenge and simplified the syntax rules. Jun 22 '14 at 12:14
• Is it case-sensitive? If yes, then your syntax list contains some case-changes. Jul 2 '14 at 2:41

# Survival of the fittest king-of-the-hill

As Chris Jester-Young suggested here, i will propose my challenge here. At the moment, this is merely a draft but i want to ask for suggestions to this idea as early as possible.

For discussions, i suggest using the chatroom at chat.stackexchange.com specifically for this challenge.

My draft in its newest state plus all source code is hosted at github where you can make pull requests with suggestions.

The post here consists of the rules my challenge will have. Look at the github to see a lengthy explanation of what i post here. Feedback of all kind is appreciated!

# Rules

Board

The challenge is held on a two dimensional board with x and y coordinates. 0|0 is on the left-top side and increases in y downwards and in x to the right. Every field on the board can only hold one object. Objects are all kind of things in the game, from resources to units and even buildings. Board corners are solid, so the board is surrounded by walls. Everything on the board is randomly distributed. The board size is determined by the number of players in the game.

Actions

Every AI acts as one faction of humans. These factions have their explicit name and can be recognized by all other factions. Each round, all factions are given the complete board state and they have to submit some actions. Actions will be executed based on the time stamp of submission. So a faster calculating AI has the benefit of moving first. Animals and NPCs will move after all actions from the AIs are executed. Then there is a new round.

Game limits

The game ends, when there is only one faction left. There can be a time limit, if is turns out to take ages... There will also be a time limit for each round. Taking more time than the limit means, your program will be cut off and the rest of your actions will be omitted. After 5 consecutive rounds hitting the time limit, an AI will be disqualified.

Gameplay

Each faction starts the game with four workers and a stockpile. They have to collect wood, stone and food to survive. Food is used up every round to fill the workers stomach. All three resources will be needed to construct buildings and advance in technology and in numbers. Workers are able to reproduce in housings. but they can also be converted to soldiers. Soldiers can not work nor reproduce, but excel in their fighting ability. With more advanced technology, workers can be converted to better soldiers. Soldiers can not be upgraded.

Strategy

There are numerous buildings available and the more advanced cost a huge amount of resources. Fighters can destroy buildings, while workers can conquer them. Buildings allow for things like reproductions, boosts on resource collection and overall attributes of each unit. Units get more experienced in things, while they are doing them. This experience is handed down to the next generation. Since there need to be two units, to get an offspring, a genetic algorithm will mix their abilities together. This can be better or worse. Your units can have offspring with units from other factions, but both units have to agree on the matter. The offspring randomly chooses between the two factions and stays there.

Control

The AI does not control its units directly. It only gives orders. There is no limit on how many orders an AI can give each turn but every unit can only have one active order at a time. Giving a second order overrides the first one. Units try to execute the orders that are given to them. They are doing this automatically and orders are carried to the next round, if they are not fully completed. While the AI hat full informations over the board, their units have not. Giving an attack order to a place the unit can't see, the unit will try to walk there and attack when in view of the target.

Alliances

There is a global chat that all AIs share and where all AIs can talk to while calculating actions. AIs can specify other AIs that they think are friendly. They can not attack these. If two AIs each think of each other as friendly, they from a bond. A chain of such bonds is called an alliance. Even if you do not consider them friendly, your alliances friends are not attackable for you. So forming an alliance with someone, who friends everyone means, you cannot attack anyone, but they can attack you, if they don't friend back. Each round you can alter your friends to your liking. There is no such thing as an alliance chat, so you have to use encryption to chat in secret. And remember, in the end, only one AI wins the game.

Scoring

Scoring is done in number of rounds survived. Perhaps there will be some more scoring factors included to make the game more interesting.

Please bear in mind, that i will edit this answer a lot the next time to reflect the changes in the challenge.

• This is rather vague at the moment. What do you want feedback on? Jul 12 '14 at 17:10
• I wanted to propose the idea of a challenge like this here first. I am at the moment thinking about the rules of the challenge. Any 'Hey, xyz would be cool!' or 'what if abc?' helps me. It will get less vague soon! Until then, every meta-feedback on the challenge is appreciated. Just speak out your mind. Jul 12 '14 at 17:16
• @PeterTaylor I have now written an outline of the rules, this challenge will have. Can you look over it and tell me, if something is unclear? Jul 12 '14 at 19:43
• I suggest to add titles to each text-section you have. It is quite hard to read right now... Jul 14 '14 at 12:04
• @Manu I have added some titles that seem to fit well. Do you have any other suggestions? Jul 14 '14 at 13:16
• @Kostronor much better :) As Peter Taylor said, everything is rather vague. Try to specify rules, such as the time limit, actions and so on... Jul 14 '14 at 13:25
• @Manu My intention for this project is to make something a bit more complex, that has many distinct strategies to win. I am writing on the controller at the moment, which helps me specify the rules in a more detailed manner. Until then, can you give me some feedback on the overall gameplay? Do you think, this could be interesting? Jul 14 '14 at 13:35
• @Kostronor Sure it is interesting. I hope it doesn't get too complicated ;) Jul 14 '14 at 13:39
• This sounds really interesting to me. However, especially due to the complexity, be prepared to get only a handful of submissions. So far the popular KotH's were popular because you could whip up a simple bot in a couple of minutes (which wouldn't have any chance of winning, but it's fun posting it anyway to get the ball rolling). If your game is sufficiently complex that even the most basic strategy takes half an hour and some debugging to implement, that will put a lot of people off (who might take this on them if there are already simpler submissions to be beaten). Jul 15 '14 at 23:06
• Btw, I really like the idea of handling commands in the order they come in! :) Jul 15 '14 at 23:06
• @m.buettner I thought, to lower the starting requirements, i will write some basic bots myself, where everyone can start. I think, the main focus should be on the strategy and not on the coding, so i will try and get some abstraction done, like the example bots from 'petri dish'. Yeah, the commands in order thing is something, that trades of better action against faster thinking. But it's a pain to implement it ;) Jul 16 '14 at 9:25

# Empire wars

This is very close to Risk, but not quite. You command an empire, composed of armies, trying to take over the world.

### The world

The world is a grid. For n competitors, the side length of the grid is sqrt(n)*4 (casted to an integer). At the beginning, the world is part of the "neutral" empire. Each neutral army contains 200 soldiers. The neutral army only defends, it never attacks. Your starting army of your empire is randomly selected from the grid. Note that the world wraps around if you go off the edge.

### Receiving soldiers

Every turn, you will be given 500 + 50t soldiers to distribute, where t is the number of armies/territories you command. You can give any amount to any army, as long as you don't exceed 500 + 50t in total.

You may then attack or transfer any number of soldiers to another location.

That means that, if you have enough soldiers, you can move soldiers from multiple different territories to multiple new territories.

### Attack/Transfer

During your turn, you may move any number of soldiers from any of your armies to any of the squares bordering your army. You can move diagonally. One of two things will happen

1. You already control the square your army is moving to: Nothing special. The new square gets some more soldiers.

2. Another empire controls the square: The two armies will fight (see below). If your army wins, the surviving soldiers will inhabit the territory. Otherwise, any surviving soldiers will retreat back.

### Battle

The order of battle is randomized every turn, because the empires who go first have a slight advantage or disadvantage (depends on the algorithm). For example, if I occupy a territory on my turn, but I go before another empire, then that empire could potentially attack my new territory.

Suppose a is the number of soldiers attacking and d is the number of soldiers defending. The defenders lose a * 0.6 soldiers and the attackers lose d * 0.7 soldiers. If the defenders have no soldiers remaining, the attacker's surviving soldiers inhabit the territory. For example, suppose the world looks like:

N-200 N-200 N-200 N-200
N-200 N-200 N-200 N-200
N-200 N-200 A-500 N-200
N-200 N-200 N-200 N-200


where N-200 represents a neutral army with 200 soldiers and A-500 represents an army of your empire. Suppose the following happens:

1. Your empire (A) decides to move 250 people north. First of all, north is not controlled by your empire, so a battle is started. N-200 loses 250 * 0.6 soldiers and A-500 loses 200 * 0.7 soldiers, with a result of N-200 --> 50 and the 250 attacking soldiers will be reduced to 110. Since the territory wasn't conquered, the 110 survivors retreat. The world will now look like:

N-200 N-200 N-200 N-200
N-200 N-200 N-50 N-200
N-200 N-200 A-360 N-200
N-200 N-200 N-200 N-200

2. You now decide to move 180 people north. The same thing happens: N-50 loses 108 soldiers and A-360 loses 35 soldiers. Since N-50 has been eliminated, the remaining 58 soldiers move into the new territory.

N-200 N-200 N-200 N-200
N-200 N-200 A-58 N-200
N-200 N-200 A-180 N-200
N-200 N-200 N-200 N-200


Note that neutral territories never attack.

### Example implementation:

The code should be in Java (thinking of extending it to other languages) and needs to extend the abstract class Empire.

// The code MUST be in the package "empire" and extend the class "Empire" from mainengine
package empire;

import java.io.IOException;
import java.util.List;

import mainengine.*;

public class TestEmpire1 extends Empire {
// Occurs at the beginning of the turn
// You get 500 + 50t soldiers to deploy
@Override
public void deploy(ArmyDeployer toDeploy) {
// Get all of my armies
List<Army> armies = getArmies();
// Distribute my new armies to each army evenly
int perArmy = toDeploy.armiesLeft() / armies.size();
for (Army a : armies) {
}
}

// You can move your armies as well
@Override
public void move() throws IOException {
// Get the world
World world = World.world;
// Get the map of the world
// Note that you can only see the areas adjacent to your armies
// All other locations appear as "null"
Army[][] map = getMap();
for (Army a : getArmies()) {
// Find the least guarded territory
Move bestMove = null;
int leastDefended = Integer.MAX_VALUE;
for (Move move : Move.values()) {
int newX = world.wrapPosition(move.getXOffset() + a.getPoint().x),
newY = world.wrapPosition(move.getYOffset() + a.getPoint().y);
if (map[newY][newX] != null && map[newY][newX].getStrength() <= leastDefended) {
leastDefended = map[newY][newX].getStrength();
bestMove = move;
}
}
// Attack with half of our strength
a.move(bestMove, a.getStrength() / 2);
}
}

}


See github for the code that will be executing it: https://github.com/prakol16/EmpireWars/tree/master/EmpireWars/src

The "number of points" that an empire receives is how many territories it controls after one run (about 50, subject to change, or so turns). The program will be run 10 times and the empire with the most total points wins.

In addition, the program creates an html file record.html which contains a record of every turn.

• Sounds interesting! :) A few comments: 1. I don't think this is very close to Risk. I'd say "inspired by Risk" is as close as it gets, because I suspect the battle system to play out vastly differently (for instance, attackers are always at a disadvantage here). 2. Up until your example it's not clear that neutral territories are occupied by some army, and that this neutral empire starts with 200 soldiers on each cell. 3. Since this caused some confusion recently, I'd remove "the world is round" (and only mention that it wraps around), because it implies that the world is spherical... [ctd.] Jul 15 '14 at 9:36
• in which case north/south wouldn't wrap around. A map which wraps on both edges is in fact in the shape of a torus, but mentioning that would probably confuse some other people, so I'd say only state that both edges wrap around and nothing else. 4. How many are "many rounds" (after which the game ends)? 5. You might want to think about providing a wrapper implementation of Empire which calls a separate process, in order to allow submissions in other languages. Like Rusher did here. 6. Can I attack and transfer... [ctd.] Jul 15 '14 at 9:40
• units from multiple territories into multiple territories within a single round? Or do I have to stick to one transfer or one (repeated) attack? 7. I suppose the order of players will be randomised? I also expect a fair share of submissions to be probabilistic. In that case deciding the overall winner based on a single run might not be fair (unless the winner is always the same submission anyway). Are you prepared to run multiple simulations if that happens (such that the winner is submission that wins the largest number of individual simulations)? Jul 15 '14 at 9:43
• @m.buettner Ok, updated some stuff. For #4, 7: I'm not sure how many yet, but it should be enough that luck doesn't affect the empire that much. For #6: Yes, you can send different commands to multiple armies in different locations. Just note that if you occupy a new territory, it won't be available for you to command until the next turn. #7. Yes, the order is randomized every turn, because if I occupy a territory, even though I can't command it immediately, another empire could still attack me immediateley. Jul 15 '14 at 14:47
• Alright, thanks for clarifying. I don't like the idea of sending your orders before everyone makes their turn. You'd have no idea what would happen to the territories you're attacking before you're actually invading there. 8. How many soldiers do I have to leave behind when attacking/transferring? Jul 15 '14 at 14:55
• @m.buettner You could potentially leave none when attacking/transferring. That would leave the territory completely undefended though. As for sending your orders before everyone makes their turn: if it isn't done this way, then the people who go first have a huge disadvantage because they don't know anything about who's attacking the territory, while the ones who go last have lots of information. Your orders should be based on what's currently there (what happened in the previous turn) Jul 15 '14 at 15:21
• If you buffer the orders, those going at the end will have a huge disadvantage because they have no idea what the map will look like when their order is actually carried out, whether there's no uncertainty at all for those going first. I think this difference is much more unfair than the first player having to make a decision before everyone else. 9. Do you get your soldiers when it's your turn or does everyone get their soldiers at the same time once everyone's moves have been completed? Jul 15 '14 at 15:32
• @m.buettner I see your point. I don't think I'll buffer the orders then (it makes more sense not to now that I think about it). 9. Everyone gets soldiers at the same time. Jul 15 '14 at 15:38
• You could look at the board game Diplomacy for some ideas about how to handle simultaneous resolution of everyone's orders. (I confess that I don't know offhand whether it's a good system, but I do know that it's a system). Jul 15 '14 at 16:42

# XKCD: (Battle of the) Hats

http://imgs.xkcd.com/comics/hats.png

Enough background, get into the game

A challenge.

You all started at a point. At the count on 3, you decides to wear yourself 1 black hat, 2 black hats or 1 white hat.

Here's what happened: (If you find this description confusing, you can look at the table below, credit to Peter Taylor)

If you use 1 black hat ->

-> If your opponent also uses 1 black hat or white hat, your opponent moves backward 1 step.

-> If your opponent uses 2 black hats, you have 50% chance making your opponent moves 2 steps backward. Else your opponent does nothing.

If you use 2 black hats ->

-> If your opponent doesn't use white hat, your move is considered successful 2 black hats attempt. Your opponent moves backward x+3 steps, where x is # of your previous successful 2 black hats attempt.

-> Else: Your attack gives no effect.

If you use white hat ->

-> If your opponent use 2 black hat, you're considered making successful white hat attempt. Your opponent moves backward y+3 steps, where y is # of your previous successful white hat attempt.

-> Else: You're considered making a failed white hat attempt. You move backward z+3 steps, where z is # of your previous failed white hat attempt.

The game ends when somebody moves 20 step backward or 10 rounds played.

If one person moves 20 or more steps backward while one doesn't, then the one who not is declared the winner.

If both moves 20 or more steps backward in the same round or no one moves 20 or more steps backward in 10 rounds, no one win.

Your bot will play 5 tournaments. In each tournament, you face each enemy once. The player who score most win in those 5 tournaments accumulated, is declared the champion

## Communication Protocol

Your bot will get this from STDIN:

id round step0 step1 move0 move 1


Where id is your player id, can be 0 or 1; round means current round (match starts at Round 1); step0 and step1 means how many step has player 0 and player 1 has taken; move0 and move1 is the move taken by player 0 and player 1.

In first round, move 0 and move 1 will be empty. In next round, it will the move as this

12w21


This means one player use 1 black hat; 2 black hats; white hat; 2 black hats; 1 black hat, respectively.

Your bot gives me output from your STDOUT as 1 if your bot want to wear 1 black hat, 2 if your bot want to wear 2 black hats, w if your bot want to wear white hat.

PS: Do aware that I use small-case "w"

Table:

                +--------------------+--------------------+---------------------+
|                    |     P0 action      |                     |
|         1          |         2          |          w          |
+---------------+--------------------+--------------------+---------------------+
|             1 | P0 back 1          | P0 back 0 or 2     | P0 back z0+4; z0++  |
|               | P1 back 1          | P1 back x0+3; x0++ | .                   |
+---------------+--------------------+--------------------+---------------------+
| P1 action   2 | P0 back x1+3; x1++ | P0 back x1+3; x1++ | .                   |
|               | P1 back 0 or 2     | P1 back x0+3; x0++ | P1 back y0+3; y0++  |
+---------------+--------------------+--------------------+---------------------+
|             w | .                  | P0 back y1+3; y1++ | P0 back z0+3; z0++  |
|               | P1 back z1+4; z1++ | .                  | P1 back z1+3; z1++  |
+---------------+--------------------+--------------------+---------------------+

• 1. The scoring table would almost certainly be easier to read in a table. 2. Could you be more precise in the definition of x, y, z? Whose previous moves are counted, and what counts as "successful"? 3. In the "You move z+3 steps", is that forwards or backwards? 4. Is it intended that the bots should not know what x, y, z are? 5. It makes more sense for the controller (of which there is one) to handle the naming issue and let each bot (maybe a dozen) handle the simple case of always being player 0. Aug 22 '14 at 11:28
• You can figure x y z from history move. For the scoring table, I cant figure out how to make this without using image (trying to make this as html as possible), I shall rewrite the 2 black hats and white hats. Aug 22 '14 at 11:36
• I agree that a table that is not an image would be better, but until you find a way to make that work, please could you include an image of a table? Aug 22 '14 at 11:47
• The table won't fit or render correctly in a comment, so I've added it to the answer. Aug 22 '14 at 11:58
• Thank you. I have credited you. Aug 22 '14 at 12:04

# Making a dichotomous key

A dichotomous key, also known as a single-access key is often used to identify plants/animals. Your task is, given a set of data, write the shortest program that outputs the shortest (in steps) possible dichotomous key. If there are multiple solutions, the program may print either one.

Input

Input will be received by stdin, or in cases where that doesn't exist (e.g. Client-side javascript) you can take input from prompt or something similar.

The input will be a list of items followed by characteristics: The format of the definition of an item will be

item[delimiter1]characteristic1[delimiter2]characteristic2[delimiter2]characteristic3


Your program may choose the delimiters. In this example, I will use : as delimiter one, and , as delimeter 2. Between each item definition is delimiter3, which will be \n in this example (but you can make it anything that isn't delimiter1 or delimiter2). Note that none of the delimeters can be [a-zA-Z] letters.

Characteristics and items are composed of a series of [a-zA-Z] characters.

Example input:

quadrilateral:fourSides
trapezoid:fourSides,onePairParallel
parallelogram:fourSides,twoPairsParallel,oppositeSidesEqual
rectangle:fourSides,twoPairsParallel,fourRightAngles,oppositeSidesEqual
rhombus:fourSides,twoPairsParallel,oppositeSidesEqual,allSidesEqual
square:fourSides,twoPairsParallel,oppositeSidesEqual,allSidesEqual,fourRightAngles


Output

Output should be written to stdout, or alert or something similar where it doesn't exist.

You must output a characteristic followed by delimiter one, followed by two integers separated by delimiter two. The first is the step to go to if the item contains the characteristic, and the second is the step to go to if the item doesn't contain the characteristic. Note that the 1st step is considered 0. Alternatively, instead of an integer, you could have an item.

Example output:

twoPairsParallel:2,1
allSidesEqual:3,4
fourRightAngles:square,rhombus
fourRightAngles:rectangle,parallelogram


This is code-golf so shortest code wins.

• The example output looks wrong to me. Shouldn't the first line be twoPairsParallel:2,1? Also, since the transformation doesn't inherently use any biology at all and since you use shapes, it would be clearer to talk in terms of "classes" or "taxons" rather than "organisms". It's also good to be explicit about I/O assumptions; since you talk about a program and string delimiters between items in a list, I would guess that you want a full program which takes input from stdin and writes output to stdout. State that. Aug 22 '14 at 8:36

This is nearly done now, just need someone to double check that everything makes sense

# Objective:

Overview:
Write a program, that given the two inputs number of rays and ray length, will produce a procedurally random array of connected points, containing the ray number, number in sequence and coordinates of each point.

Details:
The lightning is in the form of rays, which are determined by points stored as coordinates in a grid.

The initial point (0,0,0), is the cloud, where the lightning is first generated. The first ray starts here and travels out in a random direction, and will continue moving in random directions (each point has an equal chance of any direction, not influenced by the previous point), and will terminate once it reaches the ray length limit or cannot go any further (if it fails enough new direction retries when intersecting with another point). This will leave a single path between the origin and the end point.

However, lighting doesn't stay as one single ray and will fork, so while all other rays should be generated in a similar way, their origin should be randomly chosen from any of the already generated points, and the sequence then continues from this point.

The Ray Number is simply which ray iteration the code is on. Each ray is it's own individual path. The origin point of the ray will have the same coordinates as the point it branches off from.

The Number In Sequence is how many points away from the cloud (or how far into the generation) it is. If lightning forks at point 50, both separate paths will start at 51. While this is not currently used for anything aside from checking the code is working correctly, it would allow for future improvements such as animation (see gif at bottom for an example).

Coordinates are the 3D points the ray passes through. They should be stored as integers.

Simple 2D Diagram:
Here is an example output during generation after 24 points have been calculated.
The numbers written in black are the numbers in sequence, and as you can see when the 2nd ray (blue) branches out, it continues from 10. The red line is an example of when it would try intersect with existing points and get stuck. This shows the cloud as it's own ray, you are free however to do this differently.

# Rules:

• Can be written in any code (without extra plugins), although I can't guarantee anything but PHP and Python will be tested, unless someone else with access to a lot more languages helps out.
• Randomness must be seed based, so if you were to define a seed (not needed), it would produce the same result.
• A point can move in any one of the 3 dimensions - meaning it can go up, down, left, right, forwards, or backwards (x,y,z,-x,-y,-z) from the previous point, but not diagonally.
• No two points can have the same coordinates.
• The one exception of this rule is that each ray must start with the same coordinate of where it branches out (for the purpose of connecting everything together).
• If an intersection is detected, at least 3 retries must be done to find new direction, then it may be terminated. The retries must be for each point, so having 1 retry on 3 different points shouldn't terminate the ray.
• No multithreading allowed.
• The code should output the final number of points generated and time taken.
• The program should be timed to when the array of points is complete. Anything after this (such as for the bonus points) is fine and won't impact on the execution time.

# Scoring:

• Generate 100 rays with a maximum length of 200. If your code is super efficient and you want to show off, you're welcome to post the times for more complex results.
• Most efficient code wins, based on the execution time. Someone will test multiple submissions and take an average from at least 4 generations to make it more fair.

Important: So I can easily check your code works as it should, I wrote something that will display the rays in a 3D program.
You'll need to generate 30 rays with a length of 15, in 2D (easy to switch - where it randomly chooses from from 6 directions, change this to 4), and copy it to pastebin. Format it like I have done here, and keep it limited to square brackets, commas, and integers: http://pastebin.com/8XHtv4is

Bonus Points:

• Given any two random points, there is one and only path between them both. If you can code something that would be able to calculate a path between these two random points and store it in a new array with the same structure, you get 15% off the execution time.

• Instead of limited to 3 dimensions, code it for n dimensions, as more than 3 dimensions should work, despite being a little hard to visualise. If you manage you can knock 10% from the execution time.

• As not everyone will be able to do it, this is only worth 5%, but you get it, if you code a way to visually draw the rays (2D is allowed, any method is allowed, but it must be able to run at the end of the code, as opposed to copying the list into a graphing program).

# Tips:

• Start working with a 2D grid for easier debugging.
• Use small ray length and ray amount values until properly optimised.
• While intersections are fairly easy to see, diagonals are not, running the code with a single short ray to print the output can be useful.

# Example code:

Generation Time for 100x200: 75-85 seconds

length=15
forks=30
import time
import random as rd
startTime=time.time()
def getDirection(num):
if(num==1):
direction=[1,0,0]
if(num==2):
direction=[-1,0,0]
if(num==3):
direction=[0,1,0]
if(num==4):
direction=[0,-1,0]
if(num==5):
direction=[0,0,1]
if(num==6):
direction=[0,0,-1]
return direction
listOfPoints = [[0,[0,0,0],0]]
for i in range(forks):
randomPoint = listOfPoints[rd.randint(0,len(listOfPoints)-1)]
start = randomPoint[0]
newLocation = randomPoint[1]
listOfPoints.append([randomPoint[0],randomPoint[1],i+1])
j=0
j2=0
while j in range(length):
j+=1
oldLocation = newLocation
k = 0
while True:
invalid = 0
newDirection = getDirection(rd.randint(1,6))
newLocation = [oldLocation[0]+newDirection[0],oldLocation[1]+newDirection[1],oldLocation[2]+newDirection[2]]
for n in range(len(listOfPoints)):
location = listOfPoints[n][1]
if location==newLocation:
invalid = 1
newLocation = oldLocation
if invalid==0 or k>4:
break
k+=1
if invalid == 0:
listOfPoints.append([j2+start+1,newLocation,i+1])
j2+=1

print "Time: "+str(round(time.time()-startTime,2))+" seconds"
print "Generated/Maximum points: "+str(len(listOfPoints))+"/"+str(length*forks)+"("+str(round(len(listOfPoints)/float(length*forks),3))+"%)"


# Visualised Output:

(From a more advanced version I did before, I was aiming to make a flower)

• You seem to be using the word "fork" to mean two different things: a single line of points, and a bifurcation where one line becomes two. Perhaps you could use "ray" for the first, since it's conceptualised as a lightning simulator. You also seem to use "point" to mean "point in an integer lattice", but I don't think you actually state anywhere that you're working solely in integers. Aug 20 '14 at 20:26
• Is the cloud at the origin (0,0,0)? Does the first ray travel in a random direction, or always in the same direction? When the first bifurcation is created by picking a random point on the first ray, does the second ray travel in a random direction or always in the same direction? If in a random direction, what happens if the direction selected is parallel with the first ray? Aug 20 '14 at 20:26
• The explanation of bifurcation says that "However, lightning doesn't stay as one straight line, so for the second fork..." This strongly implies that each ray is a straight line. But the 2D diagram shows rays changing direction a lot. What is the correct generation process for a single ray? For the "cannot go any further" termination process to kick in, does it have to be unable to go in any direction at all, or just to pick a random direction which is blocked? (This is partially explained further down in the rules, but it would be convenient to group the explanation in one place). Aug 20 '14 at 20:28
• What is the point of the unique ID? Each tuple would already appear to have at least one primary key: the (fork number, number in sequence) pair. The later rules seem to make it clear that the coordinates are also a primary key. Separately, what are the parameters of the simple 2D diagram? In particular, what is the fork length? The red line seems to imply a lower bound of 13, but the blue line isn't that long. Aug 20 '14 at 20:28
• You can pretty much guarantee that someone will be able to test most obscure languages posted here. See also this meta thread. Up, down, left, right, forwards, and backwards are 6 directions, not 6 dimensions. It sounds like you actually want 3 dimensions. There's no point posting obfuscated example code. In general, it's better to post a reference implementation as an answer to avoid clutter. The 2D visualised output is unhelpful. I would remove it to avoid confusing people. The hand-drawn 2D image is a lot more useful. Aug 20 '14 at 20:29
• The bottleneck for many implementations could well be the I/O, so you should explain how you will take that into account when measuring performance. On the bonuses: Calculating the path between two items in a tree should be pretty simple: you track back from both until you find a common ancestor. But even though it's simple, you don't say how much of a bonus it gives. The other bonus confuses matters slightly when it says that it "should technically work for infinite dimensions": actually, it can't, because there's no fair probability distribution over an infinite set. Aug 20 '14 at 20:30
• Thanks for the comments, I'll reword the question and set it to generating lightning forks, gives it a better title. As to the potential infinite dimensions, how would you reword it? I could manually code in 100 dimensions if I wanted to spend 20 minutes doing it, I'm just suggesting someone codes the option where it'll do it automatically. Aug 21 '14 at 0:15
• Oh also, as to the bottleneck you mentioned, that's the main efficiency problem, I'm curious if anyone can find a method that doesn't involve reading the entire list every time a new point is added Aug 21 '14 at 0:42
• Hey, just updated it again, do things make a lot more sense now? Aug 22 '14 at 20:53

# Confused Automatons king-of-the-hill

## [work in progress]

This is a 1v1 (or not? could be more) king-of-the-hill, where you and your opponent both issue commands to the same, perpetually confused, gladiators and try to survive.

Toroidal arena with N gladiators. They understand the following simple commands:

• Move one of 8 directions or
• Hold

plus one of:

• Shoot target. Range of 5. Can’t shoot the following turn.
• Dodge (no target required)
• Nothing

On each turn you may issue one command ([M/H]+[S/D/N]) to each gladiator. All gladiators will execute the commands from both players each turn. Movement happens first. If a gladiator is given two shoot commands, they will shoot twice that turn; two dodge commands and they will dodge twice. One dodge will avoid one shot. A gladiator can't shoot himself. Movement in opposite directions will cancel; movement in the same direction means moving a distance of two. If there is both an [H] command and an [M] command for the same gladiator, the [H] will be ignored.

One of the gladiators is your commander. You lose when your commander dies. Your commander ignores commands from your opponent. You don’t know which gladiator is your opponent’s commander.

TBD

TBD

## Scoring

TBD

• I am just as confused as the automoton. Won't you easily be able to figure out which gladiator is the commander by seeing who ingored the command? Jul 16 '16 at 1:18