# What is the Sandbox?

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

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

## Get the Sandbox Viewer to view the sandbox more easily

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

# .... . .-.. .-.. --- .-- --- .-. .-.. -..

Another Hello World challenge, this time with Morse code!

Taking no input, your program must output HELLO WORLD in audible Morse code, printing each letter as it is played. For the purpose of this challenge, the following Morse code guidelines will be followed:

Duration of sounds:

• Dits are one time-unit long.
• Dahs are three time-units long.
• The gap between elements within the same character is equal to one dit.
• The gap between characters within the same word is equal to one dah.
• The gap between words is seven time units long.
• The length of "one time unit" is up to the programmer, so long as it is consistent throughout the message.

Letters:

• H: ....
• E: .
• L: .-..
• O: ---
• W: .--
• R: .-.
• D: -..

I'm a little iffy on that last bullet regarding duration. Should I set a hard standard, or a minimum? If so, what to?

• Set a hard minimum for timing. Otherwise, a golfed solution might have 1 unit = 1 millisecond. – PhiNotPi Dec 16 '13 at 22:23
• Tasks which take input are normally more interesting. – Peter Taylor Dec 17 '13 at 0:09
• I guess that dahs need to be a continuous tone, not just two dits without a gap? – John Dvorak Dec 17 '13 at 6:32
• @JanDvorak Correct. – Iszi Dec 17 '13 at 6:33
• If you don't plan to post this, I would like to modify it and post it. (If you don't reply to this message within two weeks, by community standards, I am allowed to adopt the challenge.) – MD XF Dec 22 '17 at 2:41
• @MDXF What do you suggest for modifications? – Iszi Jan 2 '18 at 15:18

## Code Golf: counting all colors in an image

The goal of this Code Golf is to create a program that counts all colors in an image.

### The input

The input will be a path to the image file.

### The output

The output should be a number that indicates how much different colors your program found in the image.

### The scoring

It's also important that your program supports much image formats, so I'll calculate the score based on this formula:

(character_count * 3) / (number_of_supported_image_formats * 2)


### Some other rules

• The lowest score wins
• You're not allowed to execute an external program
• No Internet access
• A color doesn't just count if it's present in the palette, there really should be pixels of that color in the image.
• You should also count pixels with 0% opacity.
• #FFFFFF with 100% opacity is not the same color as #FFFFFF with 50% (of course, this is the same for all other colors).
• In vector image formats, if there's a red square (for example) with 50% opacity that overlaps a blue square, then this should count as two colors: red and blue.
• In vector image formats, in case of a gradient, the number of colors depend on which colors are used in the gradient. For example, if there is a red/yellow gradient, then you should count this as two colors: red and yellow.
• A paletted image format is another image format than the non-paletted variant.
• SVG 1.0 is another image format than SVG 1.1 (also count for other image formats).
• What counts as a colour? Does a colour count as present if it's in the palette, even if there aren't any pixels of that colour? What about if it's present, but at 0% opacity? On the subject of opacity, are #ffffff at 100% opacity and #ffffff at 50% opacity the same colour? What about vector image formats: does a red square at 50% opacity partially overlapping a blue square count as two colours (red and blue) or three (red, magenta in the overlap, and blue)? What about gradients: does the number of colours depend on the size of the gradient-coloured object? – Peter Taylor Dec 20 '13 at 15:25
• Also, what counts as an image format? If a program supports paletted PNG but not non-paletted PNG, does that count as 0 formats, 0.5 formats, or 1 format? If a program supports SVG 1.0 and SVG 1.1 does that count as 1 format or 2 formats? Etc. – Peter Taylor Dec 20 '13 at 15:27
• @PeterTaylor: Thanks for your comments! I updated my question. – ProgramFOX Dec 20 '13 at 19:16
• I'm sorry, but I'm afraid the core of this challenge is to be as bold as possible when counting the amount of file formats my language's standard library can handle. – John Dvorak Dec 20 '13 at 19:33
• @JanDvorak: Of course, you should also look whether it's really worth to handle another image format, after you made sure to handle some other. If your score doesn't get lower, then it's not really worth. – ProgramFOX Dec 20 '13 at 19:35

Known Issues:

• Some rules seem a bit unclear to some users.
• Clarification may be needed on what is needed to qualify for the "win percentage" bonus.
• Win percentage bonus may not be enough to be a real incentive. (This may just depend on the language or implementation.)
• Perhaps the win percentage bonus should be eliminated entirely, or maybe it should just be made a mandatory part of the spec.
• It's been suggested to use a simple 1-9 numbering system for the board positions, instead of any sort of X,Y coordinates.
• May want to allow some flexibility on the input format. (i.e.: Input must still specify the sequence of moves thus far, using whatever addressing scheme is specified in the spec, but leave the delimiters - or lack thereof - up to the developer.)
• Exactly what is expected of the program, such as how it can figure out whose turn it is or what the output should be, seems to need some clarification.
• Some test cases should probably be added.
• Clarification may be needed on the matter of what parts of the game we can assume have followed the guide already.
• Some flaws exist in the chart. (Two already mentioned in comments on the original post.) These should be identified and addressed so that proper expectations for those conditions are clearly set.
• Original post said we would not have to account for null input (i.e.: X asking what their first move should be) but this might be a good enhancement to add.

I personally think this is a great challenge. So far, I've had a very hard time finding a lot of room for optimization and got up to probably 400 characters in PowerShell before I gave up (not even half-way through the chart yet) due to some of the above issues. I'd really like to see what some more serious golfers could do with this, once the spec is properly hammered out.

## Overview

This is the XKCD tic-tac-toe cheetsheet:

It's rather big, I know. But it's also your most valuable resource in your challenge.

## The challenge

Create a program (in your language of choice) that uses the Optimal Move Cheatsheet (henceforth OMC) to output the optimal move when given a sequence of moves.

## The input

Your program will be fed a series of moves in the following fashion:

A3 A2 B2 C2 ...


Where the first combination is always X, the second O, and so on. The letter is the Y coordinate (A-C, A at the top) and the number is the X coordinate (1-3, 1 at the left).

You may assume that the given combination is following the OMC's suggestion for each move at least for the player asking for a recommendation. You can also assume that the input will never be null (at least one move has been made). You must:

1. Figure out whether the next move is for X or O (you don't need to output this)
2. Use the OMC to decide the next move
3. Print the next move in the standard format A3

## Optional:

You may also include the player's chance of winning (as a percentage) for 50 character discount on your score.

• I think a 1-9 system would be easier than any XY system, but not by too much. The biggest issue I think is that if you go by the chart (rather than formulating your own algorithm that plays the same way) you have a ton of data to enter (there are several hundred squares in the two charts). Perhaps limit the input to only sequences starting A1 B2 (or 1 5 if you use telephone keypad numbering)? That's the center square in the X chart and the top left square in the O chart. – Blckknght Dec 23 '13 at 5:14
• @Blckknght Limiting the scope of the challenge makes it less interesting. Part of the challenge (if not the entire challenge) here is to find ways to shortcut the flow while still putting out accurate results. As for the 1-9 system, the simplification may be relatively trivial but it does help clear out some otherwise unneeded bloat since everyone will probably build in some conversion to a 1-9 system anyway to shorten the code. It also enables some other shortcuts where the same move suggestion applies to multiple situations which are mathematically related. – Iszi Dec 23 '13 at 19:47
• My point is that the chart data so dominates the code size that winning answers will pretty much have to ignore the data in the chart and use an AI. So the challenge becomes "write a Tic-Tac-Toe AI that plays exactly like this chart", which seems less interesting to me than "use (part of) this chart to make an AI with trivial code". I already have working code for the problem and bonus in about 200 non-golfed characters of Python, but it will require many 1000s of characters of data, even if I exploit some symmetries. Even if I was willing to type all that data, an AI will beat it, I'm sure. – Blckknght Dec 23 '13 at 20:55
• @Blckknght I'm pretty sure even a fairly straightforward implementation of the chart can be fit within about 5,000 characters - especially in a proper golfing language. IRRC, I'd finished the X portion of the chart in about 400 characters with PowerShell before I gave up on my first go at it. Even then, there was still plenty of room for optimization, and that's in a language which is far from optimal for golfing. Certainly, it's nice when you can bang out a quick answer in 15 minutes. But not every challenge has to fit in 500 characters or less. – Iszi Dec 23 '13 at 21:12

## Implement addition using only division (code golf)

Thought you could implement division using only addition? Well try it the other way around!

Your job is to make a function or equivalent program that accepts 2 numbers and adds them using only division.

## Rules

• No importing libraries
• You can't use anything dealing with mathematics except / and /=, (and their equivalents)
• No bitwise operations
• No string operations except input, output, return, and string concatenation
• Interesting. You might have to close some loopholes, though, as some people will just create a giant lookup table. Also, some people could use string operations use perform addition. Is it going to be code golf? – PhiNotPi Dec 24 '13 at 16:49
• @PhiNotPi I think so, thanks for the tip. – Timtech Dec 24 '13 at 18:42
• Does "no string operations" refer to I/O as well? It's hard to do I/O without string operations of any kind – John Dvorak Dec 24 '13 at 19:21
• @JanDvorak I want to allow I/O - how do I rephrase the question as to allow I/O without allowing math by executing strings? – Timtech Dec 25 '13 at 16:17
• "division using only division" looks like an error... – Peter Taylor Dec 28 '13 at 10:17
• Is this a code golf, code challenge or a popularity contest? – ProgramFOX Dec 28 '13 at 10:56
• @PeterTaylor Thanks :) And @ ProgramFOX, it's code golf. – Timtech Dec 28 '13 at 14:36
• @Timtech Not the number of divisions required? – Johannes Kuhn Dec 28 '13 at 15:03
• @JohannesKuhn What are you talking about? – Timtech Dec 28 '13 at 15:10
• Tried to calculate 0+0 - the only thing I accomplished was a division by zero ;-) – Howard Dec 28 '13 at 16:20
• How do you prevent solutions like Array(a).concat(Array(b)).concat([0,0]).length? – John Dvorak Dec 28 '13 at 19:53
• Is eliminating string concatenation too restrictive? Maybe only allow the built in conversions from strings to numeric types. – Tim Seguine Jan 14 '14 at 11:38
• @Tim I guess so, maybe just disallow eval/expr. – Timtech Jan 14 '14 at 11:50
• and would mod be allowed? – Tim Seguine Jan 14 '14 at 12:07
• @Tim As it currently stands, no. Do you think I should add it? – Timtech Jan 14 '14 at 15:22

## Recognize spoken numbers of .wav file

The goal of this code golf is to create a program or function that recognizes (and outputs) the spoken numbers of a Waveform Audio File (.wav).
The rules are:

1. No network access and you are not allowed to run external programs.
2. The input will be the file path to the WAV file, and the spoken text will only be one of these digits: one, two, three, four or five.
3. The output must be the recognized spoken number of the WAV file.
4. You are not allowed to use third-party libraries.
5. This is a code golf, so the code with the smallest character count wins.
• What do you mean by convert to text? Encode? Recognise spoken text? – Howard Jan 21 '14 at 18:36
• @Howard: Recognize spoken text. I updated my question. – ProgramFOX Jan 21 '14 at 18:38
• That makes it a very subjective challenge. It is quite debatable if a wav file contains recognisable text or not. I can't think of a safe way to put restrictions on the input without making it to a fixed-input kind of puzzle. – Howard Jan 21 '14 at 18:41
• @Howard: You mean, for example, ensuring that the input will only be spoken text without background music? – ProgramFOX Jan 21 '14 at 18:43
• This needs some explicit restrictions on input. I assume that you're assuming that the text will be English, but even then there is a lot of accent variety. Most speech-to-text programs which U.S. companies release can't handle many (if any) British accents in their first version or two. I think that the only way this can be reasonably objective is either to invert a TTS program (in which case it's boring - no errors to account for) or to specify a training text and a test text, where it gets to hear the training text read n times and then tries to interpret the test text. – Peter Taylor Jan 21 '14 at 18:58
• Maybe it is possible if you restrict the challenge to recognise the spoken digits one, two, three and four. Although still difficult to define clearly spoken there may be small enough variation in the input. – Howard Jan 21 '14 at 19:09
• Maybe you can make a youtube video or something similar that contains all the sound that needs to be recognized; the programs just need to cater to those sounds. – Justin Jan 21 '14 at 19:32
• @Howard: That's a good suggestion. I updated my question. – ProgramFOX Jan 22 '14 at 14:14
• What's a "third-party library"? Can C# programs use MS libraries, Obj-C programs use Apple libraries, etc? – Peter Taylor Jan 22 '14 at 16:36
• @PeterTaylor: Yes, they can. – ProgramFOX Jan 22 '14 at 17:29
• Golfing msdn.microsoft.com/en-us/library/… would make for a rather short and boring answer. – Peter Taylor Jan 26 '14 at 15:37
• @PeterTaylor, ProgramFOX: It would make sense to forbid any libraries or programs designed for speech recognition, whether third-party or not. You might want to take a look at my earlier speech synthesis challenge for some ideas on how to word such challenges (and in the comments for some issues I should've thought of in advance). – Ilmari Karonen Feb 9 '14 at 10:08

## Print Lorem ipsum

The goal of this code golf is to write a program that prints EXACTLY this text:

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

The rules:

1. No external resources
2. The shortest code in bytes wins.
• Is there any reason to expect the answers to be fundamentally different to those to existing kolmogorov-complexity questions? – Peter Taylor Jan 26 '14 at 15:33
• Won't the winner just post something like cout<<"/*text here*/";? This will probably be pretty boring, as the text needs to be hardcoded in. – user10766 Feb 6 '14 at 1:29
• @user2509848: No, I'd expect the winner to be something that packs the text in base 29 or 32 into a raw byte string and decodes it in GolfScript or some similar language. Or possibly some PHP code that starts with <?=gzinflate(. – Ilmari Karonen Feb 9 '14 at 10:00
• OK, but you will need to specify that in the rules. – user10766 Feb 9 '14 at 15:35

Here's my first proposal. It just occurred to me that it might be a bit difficult testing submissions without a functioning server, but maybe we can manage without? What do you people think?

The web hosting company I use has a jobs page that looks a bit like this:

If you want to work for them, you have to calculate the correct answer and submit it through this form. But you only have a few seconds in which to do this, so you need a script to do it for you. If you submit the correct answer in time, you're then given a hash code and an email address, and are asked to email your source code to this address, using the hash code as the subject line:

Using any language you like, write a script to download and submit this application form with the correct answer and hidden id field, and then email your source code with the hash code provided as the subject line. You can assume that the HTML source of the two pages is as follows:

# 1. http://jobs.example.com/

<!DOCTYPE html>
<html>
<title>Job Application</title>
<body>
<p>Evaluate 943 + 376 - 394 * 573 * 983 , and submit the answer with the following form.</p>
<form method="POST" action="apply.pl">
<input type="hidden" name="id" value="5d41402abc4b2a76b9719d911017c592" />
<input type="submit" name="submit" value="submit" />
</form>
</body>
</html>


# 2. http://jobs.example.com/apply.pl

<!DOCTYPE html>
<html>
<title>Job Application</title>
<body>
code to jobs@example.com with the following text in the Subject
<p><code>1a79a4d60de6718e8e5b326e338ae533</code></p>
<p>But hurry, you only have five seconds!</p>
</body>
</html>


The only variable parts of these pages are:

1. The sum (up to 6 numbers separated by any combination of +, - and * with spaces on both sides)
2. The hidden id field that must be submitted with the form.
3. The hash code on the second page

You may assume that the sum can be calculated without overflow using 32-bit integer arithmetic.

• What's the difficulty with having a functioning server? – Peter Taylor Jan 28 '14 at 15:53
• @PeterTaylor It won't be possible to actually test anyone's script without a server that can process these applications. This probably isn't a problem for sensible languages, but if someone submitted an answer written in Golfscript or Whitespace then I'd have no idea if it would actually work or not. – r3mainer Jan 28 '14 at 16:07
• It won't be possible to test them anyway if you send the e-mail to jobs@example.com. I note that you haven't specified that you're after a program: I would specify that answers should be a full program which takes HTTP URL and e-mail address as command-line arguments or as separate lines on stdin; then each person can test with an e-mail address they control. If you're willing to change the URLs a bit then I can host a couple of PHP pages somewhere under cheddarmonk.org. – Peter Taylor Jan 28 '14 at 16:34
• @PeterTaylor Ah, of course! It didn't occur to me that the email address could be separated out as input data. We'd have to change the background story a bit though. Emailing a job application to yourself seems a bit daft. – r3mainer Jan 28 '14 at 16:52
• I don't see why. If you're allowing people advance knowledge of the full HTML structure, you can assume that they have advance knowledge of the target e-mail, and then it's just a case of promoting testable code. – Peter Taylor Jan 28 '14 at 17:15

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? – John Dvorak 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". – Peter Taylor 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). – Nzall 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!! – Jonathan Van Matre 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? – Nzall 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. – Nzall 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. – Nzall 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. :) – Jonathan Van Matre Feb 28 '14 at 19:32
• What issues are you thinking about? maybe some extra rules can make this work. – Nzall 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. – ugoren 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. – 2rs2ts 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. – ugoren Feb 25 '14 at 15:20
• I caught my mistake. The score can approach infinity, not zero. Still, I think, a problem. – ugoren Feb 25 '14 at 15:22
• @ugoren Probably too many straightforward abuses to bar them all, eh? – 2rs2ts 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? – Peter Taylor 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... ;) – WallyWest 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. – Danny 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). – Howard 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.) – programmer5000 Jun 9 '17 at 16:07

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. :(

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

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 [? – Peter Taylor 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. – luser droog Jan 11 '14 at 13:22
• oh. I see what you mean now. removed mark as a separate entity. It isn't needed. – luser droog 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. – luser droog Jan 11 '14 at 13:46
• I don't see any way to create a non-identity matrix. – Peter Taylor 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. – luser droog 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. – luser droog 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. – luser droog 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.) – programmer5000 Jun 9 '17 at 16:08
• Thanks! ... Done. – luser droog 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 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
• 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 / ... – John Dvorak 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? – Geobits 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. – Victor Stafusa Mar 3 '14 at 15:28
• @JanDvorak. Ok, relaxed the databases requeriment. – Victor Stafusa 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." – Victor Stafusa 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. – Geobits 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. – Victor Stafusa 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. – Geobits 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. – Jonathan Van Matre 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. – Jonathan Van Matre 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. – Peter Taylor 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. – Victor Stafusa 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? – Nzall 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. – Peter Taylor 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. – Peter Taylor 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. – Vikram 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! – Claudiu 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. – Claudiu 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). – r3mainer 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 – Claudiu 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. – programmer5000 Jun 9 '17 at 16:19

# Create the perfect CSS reset stylesheet

Your job is to create a CSS reset stylesheet, That is, a stylesheet that you can apply to any HTML file, and the result will look the same in all webbrowsers. Because we all know that cross-browser interoperability is very important these days, and you want to make your website look pixel perfect everywhere.

The rules:

1. You must be able to throw any valid HTML5 document at it and the result will look the same in the main browsers.
For simplicity, you can assume that the HTML document does not contain any styles of its own or Javascript that changes anything. Just pure, static HTML that is valid HTML5.
2. The main browsers are Firefox >= 22, Chrome >= 28 and IE >= 10.
3. To avoid solutions like *{display:none} (which do indeed make all documents look the same in all browsers, yes) the result must be identical to the document without the stylesheet in one of the browsers.
In other words, take your browser of choice and make the document look like that in the other browsers.

The winner is the stylesheet that works the best, again, on any HTML file that is valid HTML5 and uses no other styles. I'm not looking at efficiency. If you come up with a 100K stylesheet or one that slows the site down considerably, that doesn't matter, as long as the end result looks good.

That's the question so far. Now I have a bit of a problem with "any HTML5 document"; I know I could provide a test document that people can work with, but then you'll get answers that cater to only that particular test case, and that's not what I want. Not sure how to handle this. Ideas?
Also, I want to include Safari as a main browsers, but as I don't have a Mac, I can't test the results on it. Not sure how to handle that.

• – Peter Taylor Mar 14 '14 at 12:59
• @PeterTaylor That breaks rule #3. – Mr Lister Mar 14 '14 at 13:05
• The result must be identical to the document without the stylesheet in one of the browsers. I assume you have loaded a webpage without a stylesheet before? If you mean that it can have the main stylesheets, and we just need to create a modification stylesheet, you should specify that. – user10766 Mar 14 '14 at 16:17
• @hosch250 What I mean is that I want the document to retain its basic HTML-ness, so it shouldn't look like plain text. Take this fiddle for example; open it in all browsers, and then add CSS to it so that it looks like (your favourite browser) in all other browsers. If the name of such is "modification stylesheet" rather than "reset stylesheet", I apologise. – Mr Lister Mar 14 '14 at 19:32
• OK, I was thinking about how most HTML pages rely on CSS stylesheets to even be legible. If you took the CSS sheet off any webpage, it would not look the same; in fact, if the HTML wasn't laid out good using accessibility techniques, it wouldn't be legible. – user10766 Mar 14 '14 at 20:01
• Pixel perfect isn't going to happen because of issues around anti-aliasing: CSS doesn't let you do things like enable ClearType on Safari/OS X or disable it on IE/Win. So the best anyone can do is somehow obtain the default stylesheets for the listed browsers (e.g. iecss.com but updated) and then find a minimal diff. – Peter Taylor Mar 14 '14 at 20:09
• Guys, I'm not interested in solutions to the question right now. I want to know if the question is OK! Specifically if I can get away with not posting a testcase like the fiddle above. – Mr Lister Mar 14 '14 at 20:38

# 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. – kitcar2000 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... – trichoplax Apr 16 '14 at 9:23
• @kitcar2000 I also think that time is important. Why did you add another proposal? – Martin Thoma Apr 16 '14 at 9:33
• @moose Sorry, I accidentally undeleted it. – kitcar2000 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. – Peter Taylor 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. – bazzargh 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. – durron597 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. – trichoplax 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? – trichoplax 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. – trichoplax 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. – durron597 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. – durron597 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? – trichoplax 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. – trichoplax 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. – trichoplax 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... – trichoplax 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. – trichoplax 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! – durron597 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... – trichoplax 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! – alexander-brett Apr 20 '14 at 20:42
• Why ask people how fast code ran on their machine? Different computers run at different speeds. – golfer9338 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 – george Dec 2 '16 at 23:07
• @george Sure. Please let a link here so that I can have a look at the question. – Martin Thoma 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? – John Dvorak 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 – Cruncher 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. – Justin 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. – Cruncher May 9 '14 at 15:26
• @Cruncher Yes. I need to go and fix it. – Justin 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? – trichoplax 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. – luser droog 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. – trichoplax 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. – trichoplax 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... – trichoplax 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. – Isiah Meadows 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? – Kyle Kanos Jun 19 '14 at 18:48
• @KyleKanos: Followed closely by any language with an eval function/operator. – Dennis 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. – Kyle Kanos Jun 19 '14 at 18:57
• @KyleKanos: eval("entire code goes here"); has two tokens and doesn't violate those rules. – Dennis 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. – Jwosty 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. – Kyle Kanos 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. – Dennis 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? – Jwosty Jun 19 '14 at 19:35
• Also, @KyleKanos: I think I fixed the wording in the beginning. Does it read clearly now? – Jwosty 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. – Kyle Kanos 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. – Jwosty 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. – Dennis 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? – Peter Taylor 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. – Jwosty 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?

• 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. – Isiah Meadows 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. – Jwosty Jun 23 '14 at 15:30
• @Jwosty: what if the "dangerous operation" part was changed to "suddenly draws a christmas tree" (or sth similar)? – liori Jun 23 '14 at 19:18
• That would be a different contest, so I would post that as another answer – Jwosty 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.) – Martin Ender 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. – Martin Ender Jun 30 '14 at 20:23
• @m.buettner I liked your suggestions. Please tell me what do you think now. – Ilya Gazman 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. – Martin Ender 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. – Peter Taylor Jun 30 '14 at 22:35
• @PeterTaylor Got you, how about now? – Ilya Gazman 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. – Peter Taylor 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 – Ilya Gazman 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? – Martin Ender 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. – Martin Ender 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. – Martin Ender 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. – Martin Ender 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 – Martin Ender Jun 30 '14 at 21:01
• @m.buettner see update. Is that better? – Dan Jun 30 '14 at 21:03
• yup, have an upvote – Martin Ender 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 – Peter Taylor 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 – Rainbolt 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. – Rainbolt 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. – Rainbolt 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. – Peter Taylor 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. – Peter Taylor 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. – Peter Taylor 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. – r3mainer 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 :-) – r3mainer 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? – Martin Ender Sep 1 '14 at 10:03