# What is the Sandbox?

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

To post to the Sandbox, scroll to the bottom of this page or click on the "Add Proposal" link below, and click "Answer This Question". Click "OK" when it asks if you really want to add another answer. Write your challenge just as you would when actually posting it. You may also add some notes about specific things you would like to clarify before posting it. Other users will help you improve your challenge by rating and discussing it. When you think your challenge is ready for the public, go ahead and post it, replace the post here with a link to the challenge and delete it.

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

## 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]

• How are tags added to questions? – guest271314 Jan 9 '19 at 7:51
• @guest271314 You can use this markup to create a tag in a draft: [tag:code-golf] – DJMcMayhem Aug 29 '19 at 15:19
• Why no featured anymore? Can't we have it auto-added or something? – S.S. Anne Sep 26 '19 at 15:57
• @JL2210 We now have a permanent info box that links to the Sandbox, so the featured tag isn't necessary – caird coinheringaahing Sep 29 '19 at 13:43
• $y=mx+c+abcdef$ – Rebecca J. Stones Jan 4 at 3:14

# Huffman Decoding

Write a programm which takes two strings as input and prints a text.

The first argument is a Huffman Tree, serialized in the following format:

• every ascii character except ~ is always a leaf, if ~ is the first characater it is also a leaf.
• <tree0><tree1>~ is a tree where <tree0> is the left subtree and <tree1> is the right subtree.

Example: ab~cde~~~ generates this tree:

 ┌─┴─┐
┌┴┐ ┌┴─┐
a b c ┌┴┐
d e


where a would have the key 00, b 01, c 10, d 110 and e the key 111.

The second argument is a text that has been compressed with with the Huffman code that is defined by the first parameter. This bit-string can contain any bit sequence (also null-bytes and non-printable characters) and is not byte aligned, therefore it has been encoded with a variation of the standard Base64 encoding:

• the characters used for the encoding are the standard base64 characters: ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/
• the bitstring is broken up into 6-bit chunks and mapped to this characters
• if the last chunk is smaller than 6 bits, a character with this prefix is used, and padding characters are added to the string:
• - : the last chunk was five bits long
• = : the last chunk was four bits long
• =- : the last chunk was three bits long
• == : the last chunk was two bits long
• ==- : the last chunk was one bit long

Example:

bits:       1 1 1 1 0 1 1 0 1 0 0 1 1 1 0 1 0 1 0 0 0 1 1 0 1
chunks:    |1 1 1 1 0 1|1 0 1 0 0 1|1 1 0 1 0 1|0 0 0 1 1 0|1[0 0 0 0 0]|
characters:       9           p           1           G           g
base64:     9p1Gg==-


Your programm has to decode the text encoded in the second parameter and print it to stdout.

You have to provide your source code encoded in the way described above. The length of your encoded source code + the length of your serialized huffman tree will be the winning criterion.

TODO: example input

• It would be helpful to explicitly state the 64 characters used in the encoding. I presume they're A-Za-z0-9+/ but (especially if you're expecting people to implement that part explicitly) it's best to make the problem self-contained. – Peter Taylor Oct 8 '12 at 16:23
• 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 15:30

## Compile BF to TM

Your task is to write a compiler accepting a Brainfuck program (previous challenge: Interpret Brainfuck, wikipedia: Brainfuck) as input and outputting a Turing Machine which produces identical output when supplied with the same (correct) input.

You may select the output format from among the various formats accepted by the answers to Turing Machine Simulator.

The following links may also be useful.
An introduction to programming in BF
BF is Turing-complete
Programming a Turing Machine
Programming Praxis: Turing Machine Simulator

Equivalently, you may write a Brainfuck interpreter in TM, or any partial compilation/interpretation which results in a TM program as described above.

If we consider squares of the TM tape to represent bits (blank=0, mark=1) of the BF memory, then eight squares represent a cell. Each BF instruction translates to a minimum of 8 states of the Turing Machine.

'>' "advance" (++ptr) could be implemented by eight states (sixteen transitions):

adv8 _ adv7 R _
adv8 1 adv7 R 1
adv7 _ adv6 R _
adv7 1 adv6 R 1
adv6 _ adv5 R _
adv6 1 adv5 R 1
adv5 _ adv4 R _
adv5 1 adv4 R 1
adv4 _ adv3 R _
adv4 1 adv3 R 1
adv3 _ adv2 R _
adv3 1 adv2 R 1
adv2 _ adv1 R _
adv2 1 adv1 R 1
adv1 _ link R _
adv1 1 link R 1


where 'link' represents the first state of the following instruction.

'<' "rewind" (--ptr) can be implemented similarly by making leftward movements and rewriting the same symbol just read.

'+' "increment" (++*ptr) can be implemented by a ripple-carry from the Least Significant Bit to the Most Significant Bit, borrowing "rewind" states to back-up to normal position. If the LSB is on the left, it would look something like this:

inc8 _ link N 1
inc8 1 inc7 R _
inc7 _ rew1 N 1
inc7 1 inc6 R _
inc6 _ rew2 N 1
inc6 1 inc5 R _
inc5 _ rew3 N 1
inc5 1 inc4 R _
inc4 _ rew4 N 1
inc4 1 inc3 R _
inc3 _ rew5 N 1
inc3 1 inc2 R _
inc2 _ rew6 N 1
inc2 1 inc1 R _
inc1 _ rew7 N 1
inc1 1 overflow N 1


where overflow is a HALT state.

For I/O, the simplest way I can think is to place all input on the tape after the memory area, and expand the alphabet to include a symbol indicating the dividing line between the memory portion and the input portion of the tape. In fact, by expanding the cell size to nine squares, this symbol can serve as an input pointer, advancing as the input is consumed. (So "advance" and "rewind" now need 9 states each.) And another new symbol is written in front of the current memory cell to serve as the memory pointer. Inputting a byte therefore consists of schleping each bit over the entire space between the two tape positions with something like this:

input _ set-memptr L _
input 1 set-memptr L 1
set-memptr _ find-inptr R *
find-inptr _ find-inptr R _
find-inptr 1 find-inptr R 1
find-inptr $schlep-bit R$
schlep-bit _ schlep-blank L _
schlep-bit 1 schlep-one L 1
schlep-blank $schlep-blank L$
schlep-blank _ schlep-blank L _
schlep-blank 1 schlep-blank L 1
schlep-blank * deposit-blank R *
schlep-one $schlep-one L$
schlep-one _ schlep-one L _
schlep-one 1 schlep-one L 1
schlep-one * deposit-one R *
deposit-blank _ etc R _
deposit-blank 1 etc R _
deposit-one _ etc R 1
deposit-one 1 etc R 1


where "etc" represents going to get the next bit in similar fashion.

To perform a loop (all BF loops are "while" loops, so the exit control is at the beginning and the end has a simple goto back to the beginning), we need first to check is the current cell is zero,

zero8 _ zero7 R _
zero8 1 body R 1
zero7 _ zero6 R _
zero7 1 left1 L 1
zero6 _ zero5 R _
zero6 1 left2 L 1
zero5 _ zero4 R _
zero5 1 left3 L 1
zero4 _ zero3 R _
zero4 1 left4 L 1
zero3 _ zero2 R _
zero3 1 left5 L 1
zero2 _ zero1 R _
zero2 1 left6 L 1
zero1 _ exit-loop R _
zero1 1 left7 L 1
left7 _ left6 L _
left7 1 left6 L 1
left6 _ left5 L _
left6 1 left5 L 1
left5 _ left4 L _
left5 1 left4 L 1
left4 _ left3 L _
left4 1 left3 L 1
left4 _ left3 L _
left4 1 left3 L 1
left3 _ left2 L _
left3 1 left2 L 1
left2 _ left1 L _
left2 1 left1 L 1
left2 _ loop-body L _
left2 1 loop-body L 1
...
loop-body-final _ zero8 N _
loop-body-final 1 zero8 N 1


So assuming the machine starts at tape-location 0, and the input is on the tape starting at 0 and going to the right, the "startup code" for this arrangement would be

startup _ place$L _ startup 1 place$ L 1
place$_ left270000 L$
left270000 _ left269999 L _
...


Jeez! The output is going to be HUGE! It might be better to treat the BF memory as negative-indexed and reverse all the _L_s and _R_s in 'advance', 'rewind', 'increment', and 'decrement'.

Questions:

Bonuses for optimizations? If I can implement this myself and provide a complete example output, The bonus could be "subtract the difference between your program's output for the example input with the example output". So eliminating states would be far more valuable than shrinking the code. One could possibly achieve a negative score!

Edit: Actually I think this is unreasonable unless the Turing Machine is augmented with non-reading (movement-only or epsilon) transitions. Duplicating every letter of the alphabet just to move over one square is just ridiculously painful. That means this challenge won't link-up nicely with the other one. :(

What about, instead of implementing the compiler, just devise a translation scheme (as above) that leads to a smaller output for a trivial sample program (based on calculating, rather than coding)? "Back of the envelope" compiler.

• "How much detail on BF do I need to supply? Can I simply reference the BF question?" A link to almost any site that describes the language will do. – dmckee --- ex-moderator kitten Nov 5 '12 at 16:52
• Winning condition? – Peter Taylor Nov 6 '12 at 13:43
• "Longest prefix containing syntactically-correct Malbolge!" :) ... I'd say have none at all. Perhaps the questioner should be required to accept their own example answer? – luser droog Nov 6 '12 at 18:08
• @PeterTaylor Apologies for my last comment. I thought we were on my other answer about the [fun] tag. . . . This one would be a golf: shortest code by character count. But I think a clever system of bonuses could make it interesting. – luser droog Nov 7 '12 at 10:06
• The "Equivalently, you may write a Brainfuck interpreter in TM" option doesn't play very well with being a code golf - how are you going to count the length of the TM? – Peter Taylor Nov 7 '12 at 11:15
• @PeterTaylor Since the TM question specified 5-tuples, I think it's sufficient to count the tuples (== transitions). You can reduce states by increasing the alphabet (or vice versa), but the transitions would remain constant, I think. – luser droog Nov 8 '12 at 5:25
• Can we delete this because the sandbox lags so much and this hasn't been touched in 5 years? – programmer5000 Apr 13 '17 at 17:42
• I'd like to adopt (work on and post) this challenge if you don't want to. Would I be able to? If you do not respond to this message within two weeks, by community guidelines, I am allowed to take it over. – MD XF Aug 18 '17 at 3:23
• Yes, please. If you can do something with it, strike while the iron is hot. – luser droog Aug 18 '17 at 4:19

# Graphical Output -- Esoteric Artifacts -- The Glass Bead Game

## Draw the Cabalistic Tree of Life

Simply described, the Tree of Life is an undirected network of nodes representing the conduit between matter and higher forms of spiritual energy. It has an upper face arranged in a hexagon, and a lower fact built from equilateral triangles adjacent to the lower two edges of the upper face. Don't label the paths, paths may overlap however you wish, may be single (thick) lines, even. Code Golf. Bonus -100 for labels on the Sephiroth (nodes); Bonus -150 for Hebrew labels.

## Draw a Mandala for each Natural Number

Draw a circle with interesting visual patterns using the input N [ 1 .. \inf ) to determine the number of points around the circle to anchor figures whose shape is also modified by the input N. Actually, 12 seems like a good max: they're pretty much a blur after that no matter what.

Eg. http://code.google.com/p/xpost/downloads/detail?name=ve6a.ps
//lotsoflines n = 1 ..12

(doesn't need to be this elaborate, This is >600 lines of showing-off.).

. . . need good images for these . . .

## Draw the Ptolemeic System of the Universe

All the stuff I could find is animated already. Maybe this one's done-to-death. :(

Update: Found good stuff on Alchemy. The "Keplar Platonic" model could be fun (3D and all). This one looks good, too. And this.

## Draw the Pythagorean Monochord

aka pre-classical nomogram. I misplaced my Pythagoras books, I know I've got a picture somewhere.

This is the one I was thinking of.

But I think this one's even cooler

## Draw the I-Ching Hexagrams in King Wen Sequence.

I suppose I need to implement this first to avoid copyright issues! :)

• The I-Ching one would have to be in standard order to be remotely interesting, and then becomes as much about kolmogorov-complexity as graphical-output – Peter Taylor Nov 22 '12 at 21:24
• For the others: images, please! – Peter Taylor Nov 22 '12 at 21:25
• I've emailed the owner of the Alchemy pages asking for permission to use his copyrighted images. Awaiting response. – luser droog Jan 28 '13 at 8:25
• Can we delete this because the sandbox lags so much and this hasn't been touched in 5 years? – programmer5000 Apr 13 '17 at 17:42

## Polygon prefixes

Polygons are named after the number of sides that they have. A pentagon has 5 sides, an octagon has 8 sides. But how are they named? What's the name for a 248-sided polygon?

All polygons are suffixed with -gon. There are specific prefixes for each polygon depending on the number of sides. Here are the prefixes for the lower numbers:

3 - tri
4 - tetra
5 - penta
6 - hexa
7 - hepta
8 - octa
9 - nona
10 - deca
11 - undeca
12 - dodeca
13 - triskaideca
14 - tetradeca
15 - pentadeca
16 - hexadeca
17 - heptadeca
18 - octadeca
19 - nonadeca
20 - icosa


Polygons with 21 to 99 sides have a different system. Take the prefix for the tens digit (found on the left column), the ones digit (right column below), and then stick a "kai" between them to get (tens)(ones)gon.

20 - icosi       | 1 - hena
30 - triaconta   | 2 - di
40 - tetraconta  | 3 - tri
50 - pentaconta  | 4 - tetra
60 - hexaconta   | 5 - penta
70 - heptaconta  | 6 - hexa
80 - octaconta   | 7 - hepta
90 - nonaconta   | 8 - octa
| 9 - nona


The 3-digit sided polygons are named in a similar fashion. A 100-sided polygon is called a hectogon. Take the hundreds digit, find it on the column for ones digits, then stick a "hecta" to its right. Now number off the tens and ones like above: (hundreds)hecta(tens)(ones)gon. If the hundreds place digit is a 1, don't put the prefix behind "hecta".

So, given an integer (3 <= n <= 999), return the name of an n-sided polygon. n-gon is not a valid answer :P

As with all code golf, shortest code wins.

Is the description good? Would it be harder if I instead asked for the number of sides, given a name?

• What is a 101-sided figure called? "hectahenagon"? Is "hena" from the column for ones digits you mention? If so, then what is a 111-sided figure called? I'd say "hectaundecagon", but then that comes from a column where "hena" is not present. – Gaffi Feb 11 '13 at 11:15
• @Gaffi: Yep, it's hectahenagon, from what Google says. – beary605 Feb 11 '13 at 16:03
• Can we delete this because the sandbox lags so much and this hasn't been touched in 4 years? – programmer5000 Apr 13 '17 at 17:43
• I am going to take this if you allow me or if you don't respond – Christopher May 30 '17 at 1:13

## Self-Golfing Code?

I don't know if I just didn't search hard enough, but I couldn't find any challenge regarding self-golfing code, or rather, any code that can deterministically reduce another set of text code to a much smaller program, yet still compile/run.

For example, take this:

int main() {
std::cout<<"Hello world 1!"<<std::endl;
std::cout<<"Hello world 2!"<<std::endl;
std::cout<<"Hello world 3!"<<std::endl;
std::cout<<"Hello world 4!"<<std::endl;
std::cout<<"Hello world 5!"<<std::endl;
}


And output this (as one possible solution):

#define A std::cout<<"Hello world
#define B !"<<std::endl;
#define C B A
int main() {
A 1 C 2 C 3 C 4 C 5 B
}


Alternative:

Sub MySub()
Dim aNumber As Integer
Dim someString As String
aNumber = 123
someString = "abc"
MsgBox aNumber
MsgBox someString
End Sub


into (again, as one possible solution)

Sub m()
Dim a As Integer
Dim s As String
a = 123
s = "abc"
MsgBox a
MsgBox s
End Sub


Do we have a challenge for this?

If not, here are some rules I envision:

• Golfing code need not be in the same language as code to be golfed.
• Since compilers/running of code varies, newly golfed code must still run under same environment.
• Possible challenge scoring (multiple options -- thinking code golf):
• 1: Shortest golfing code wins (not my favorite, since you can minimally shorten the base code, yet still write the shortest program).
• 2: Shortest output of a set of pre-defined code (potentially limiting if participants are unfamiliar with the options available)
• 3: Combination of length of golfing code and the output result of the same as input. (Ratio, summation, etc.) -- This I think is my preferred option.
• 4: Multi-player Ratio of golfed size of other participants' own code versus their original submission. (Similar limitations to that of point #2.)
• Sounds more like an auto-golfer than obfuscation. Seems like it would be very hard to make it a fair contest unless you pick a language to golf, and even then it had better be a simple language (no platform dependency issues or compiler options). – Peter Taylor Feb 13 '13 at 15:15
• @PeterTaylor My examples are golfing, but either would work. Perhaps golfing would be simpler, then? I agree that the options for usable languages makes this a bit messy... Would one challenge per language be acceptable? (i.e. aligned with most challenges that are language-agnostic) – Gaffi Feb 13 '13 at 17:36
• Language-agnostic to mean means that you can write a program to do it in any language. Since the language to be golfed can be different from the submitted program, I don't see any incompatibility between making the problem "Write a program to golf Piet" and being language-agnostic. – Peter Taylor Feb 15 '13 at 0:18
• @PeterTaylor So then you see no problem with one question per language on which to operate? Are there any proposed scoring algorithms you particularly like/dislike? – Gaffi Feb 15 '13 at 12:02
• That depends on what you mean. If you're planning to post 10 questions at once, yes, that would be a problem. But I don't see a problem with posting a well-defined "Auto-golf Piet" and following it up two months later with "Auto-golf Perl 5". – Peter Taylor Feb 16 '13 at 10:19
• Scoring is an issue. The halting problem means that it's impossible to write an optimal solution, so the scoring must take into account how good the solution is. I think option 3 is the best, and you'll want a big test set (maybe a few kB taken from a real-world open source project) with coverage of the language features. – Peter Taylor Feb 16 '13 at 10:22
• Can we delete this because the sandbox lags so much and this hasn't been touched in 4 years? – programmer5000 Apr 13 '17 at 17:43
• Btw, your first example doesn't work. You can't have unmatched quotes in preprocessor directives. Don't know why. – MD XF Jan 13 '18 at 18:03
• I honestly think this would be fine if you did something like solely maco-golfing, making it somewhat language agnostic because of gcc -E. – Zacharý Nov 10 '18 at 14:36

## DeCSS

It is known that the DVD Content Scrambling System can be deciphered with a rather short program (434 bytes of C, 472 bytes of Perl). Can you do better?

<< Test cases go here >>

I don't plan to include a more detailed spec, because it will just wind up duplicating some of the code. The test cases would be in the form of (key, link to data file, md5sum of the deciphered stream).

• And the winning criterion is who is the first to get post from the courts? – celtschk Oct 3 '15 at 20:18
• @celtschk, I think that would be unfair. Winning criteria shouldn't really depend on where people live... – Peter Taylor Oct 10 '15 at 20:56
• I think you should at least explain the general concept of the spec. – Rohan Jhunjhunwala Aug 2 '16 at 22:53
• This actually sounds interesting. @PeterTaylor Perhaps you could use (and link to) Charles Hannum's explanation of the algorithm and post this. (It would be fun to have it as a popularity contest for a program that looks like it's nothing DeCSS related, or a program that furthers the gallery's point about the text vs source code arbitrary distinction - but I don't know if popularity contests are popular any more!) – sundar - Reinstate Monica Jun 25 '18 at 8:25

# Missile Command

I'm making this CW, because it needs lots of help. I've been toying with this idea for a while. Think "battleship" to get in the right mind-frame. But, instead of ships, what you lay down are tiles which represent a Befunge-style program. This program controls the behavior of guided missiles ejected from the spawn tile. The goal is to program a missile which will obliterate an opponent's program block, as well as guard its own control block.

Haven't nailed-down the board size. 20x20 seems a little cramped.

         1         2
12345678901234567890
____________________1  4x20 program block
____________________2
____________________3
_______@____________4
....................5  12x20 arena
....................6
....................7
....................8
....................9
....................01
....................1
....................2
....................3
....................4
....................5
....................6
___________@________7  4x20 program block
____________________8
____________________9
____________________02


## Tiles

@ spawn

Program control.

I'm imagining these to change direction of the code for "boustrophedon" writing.

this,then\
txen,siht


haven't thought it all though, yet.

/

\

Movement.

F forward move forward one square

B back move back one square

L left turn left 90°

R right turn right 90°

So the submissions would be 4x20 code blocks which compete in a king-of-the-hill style.

• If this is deterministic, won't it be "Last person to submit their program wins"? – Peter Taylor Jun 7 '13 at 8:39
• That is a danger, yes. I'm hoping ways around it can be found. There could be a random operator. And proximity detection, or something. – luser droog Jun 7 '13 at 8:46

## Code golfing problem: Surface classification

The task: Given a surface-word reply with the classification of what surface it is.

Example 1: Input: aba'b' ----> Output: 1T

Example 2: Input: aabcb'c' ----> Output: 3P

Bounds on the problem: Since there are only 26 letters, there will never be more than that many labels. Additionally output should be in the form S,nT,mP for n,m positive integers.

Background: In the study of algebraic topology students are often presented with diagrams such as the one below. The represent instructions for how to assemble a surface. The assembly is prescribed as: if there are two edges labeled with the letter x then glue them together so that the arrows point the same direction. To make our job easy, topologists have discovered an algorithmic way to classify surfaces using 'words' assembled from these 'plane gluing-diagrams'.

Choosing a corner arbitrarily (top right) and orientation (ccw) we read off the labels on the edges where an inverse appears wherever the arrow points against the orientation. In this case the 'word' that represents this plane model is given as abab.

A surface word is a string that contains the letters a,b,...,@ up to some letter @ and each letter is contained in it exactly twice. In the two occurrences of each letter: 0, 1, or 2 of them may be postfixed by a ' which I am considering using to represent 'inverse' (opposite orientation).

If in a surface word all letters appear twice: once without the ' and once with it (f.ex. ba'b'a) then we say that the surface the word represents is orientable. If a surface is orientable then it is necessarily the direct sum of n Tori for some non-negative integer n. If this condition doesn't hold (like in aab'b) then the surface represented is non-orientable: in this case it is the direct sum of m Projective Planes for some positive integer m.

Once you have found out if the reduced word is orientable or not, the final answer is given as follows. If orientable and number of unique letters in the reduced word is 1 then output should be S. Otherwise if the number of unique letters in an orientable word is n (it will be even) then the output should be sT where s = n/2. If the word is non-orientable then the output should be mP where m is the number of distinct letters in the reduced word.

The goal is to take as input some surface word, reduce it via reduction rules 1-6 and then classify it as a sphere, some number of connected tori, or some number of connected projective planes. Here are the 6 reduction rules where ~ represents 'reduces to':

Let M,A,B,C,D be surface words, x be a single letter, and juxtaposition represents concatenation:

1. Cycle Rule: If M = AB then M ~ BA
2. Flip Rule: M ~ M'
3. Sphere Rule: Axx'B ~ AB
4. Block Rule: ABC ~ ADC if B is a surface word and B ~ D by 1 or 2
5. Cylinder Rule: If M = AxBCx'D, then M ~ AxCBx'D
6. Möbius Rule: If M = AxBxC then M ~ AxxB'C ~ AB'xxC

I am looking for input on:

• should this be code-golf or programming-challenge?
• how would scoring work?
• ???

If I feel satisfied with the question in a few days I'll post it to the site.

• If, for each input, there is only one correct output, then it should probably be code-golf. The scoring criteria would then be source code length. – PhiNotPi Jun 8 '13 at 14:33
• Yes, this is the case. In general however there is not a unique series of applications of the reduction rules for any given instance. – Kaya Jun 8 '13 at 16:21
• I don't think the order of explanation is correct. You should explain reduction before talking about "the reduced word". And "reduce it via reduction rules" doesn't entirely make sense, because the rules are presented as equivalences rather than reductions, and most of them don't have a "natural" direction. – Peter Taylor Jun 10 '13 at 8:49
• It's also occurred to me that you haven't defined the notation M'. Does it just consist of toggling the orientation of each token, or does it also reverse the entire string? And do you have test cases which between them force implementation of all of the reduction rules? – Peter Taylor Jun 11 '13 at 8:32
• Good call on the string inverse, yes you have the right idea and I will make it clear. I have a lot of test cases from when I did a number of these computations by hand in a university course and (anecdotal experience) I am pretty sure that it is possible to force the use of all the reduction rules (except maybe 4 which is really just a meta-rule for convenience when doing proofs). Additionally you have alerted me to some concerns regarding the form of the proper output: it's definitely underspecified. I'll put some work into this today. – Kaya Jun 11 '13 at 14:04

## Find all of the Scrabble numbers:

A scrabble number is a number n whose scrabble representation can score n points. As an example consider 12: its English spelling twelve has value 12 when it is placed on a stretch of six blank tiles. Since the highest ever reported 1 word scrabble score barely exceeds 2000 points, that will be the upperbound for this challenge.

Score and quantities for English:

2 blanks |  x1  |  x2  |  x3  |  x4  |  x6  |  x8  |  x9  |  x12 |
1    |      |      |      | LSU  | NRT  | O    | AI   | E    |
2    |      |      | G    | D    |      |      |      |      |
3    |      | BCMP |      |      |      |      |      |      |
4    |      | FHVWY|      |      |      |      |      |      |
5    | K    |      |      |      |      |      |      |      |
8    | JX   |      |      |      |      |      |      |      |
10    | QZ   |      |      |      |      |      |      |      |


Considerations for either bonus points to scoring or extra requirements:

• Respect the board, only using gaps between double/triple letter and double/triple word scores that occur on a standard scrabble board.
• Respect the tile count for each letter.
• There are non-English versions of scrabble, maybe it should be 'language-agnostic' (lol, but seriously is there a reason to accept only English submissions?).
• Should the 2 blanks be allowed?
• What about tiles which were already on the board and so wouldn't score anything? As for language: one approach would be to make it take the names of the tiles (and perhaps the values and counts of the letters) as input; this would also prevent the problem from being effectively one of Kolmogorov complexity. – Peter Taylor Jun 19 '13 at 22:50
• I don't believe that tiles on the board already would pose an issue. If you assume that the board may be prepared with any subset of the tiles beforehand (some may be impossible, but checking that is out of scope) all that is relevant to the problem is which are placed to complete the word. All the tiles points are counted, even the earlier placed, but only the new 7 (or less) tiles may qualify for triple/double-word/letter scores. w.r.t. kolmogorov, If I wanted to make it programming challenge instead of codegolf (so that isn't an issue) then there needs to be a scoring system right? – Kaya Jun 19 '13 at 23:33
• Yes, if it isn't codegolf then it needs a scoring system. I'm not sure what you could use as an alternative scoring criterion, though: it's simple enough logic that pretty much any implementation would be IO-bound, so speed doesn't work; and big-O based tends to be less straightforward than you might think. – Peter Taylor Jun 21 '13 at 11:05

# Sort all lines according to their corresponding Levenshtein Distance to the first line.

Shamelessly borrowed from: http://golf.shinh.org/p.rb?Levenshtein+Distance+Sort+FIXED

For a definition of the Levenshtein Distance, look here: http://en.wikipedia.org/wiki/Levenshtein_algorithm

Rules:

Takes input from stdin. Must work for all possible input. Get points for:

Smallest character count. Using Languages that are difficult to golf in. I think character count / the average values from here (http://golf.shinh.org/lranking.rb) might suffice?

• There are a number of ambiguities in the problem description. What is the correct behaviour if the input is empty? In the general case, should the first line be included in the lines which are sorted and output? Should the sort be by ascending or descending edit distance? How should ties be broken? – Peter Taylor Jun 25 '13 at 20:23
• As for handicapping: are you going to prohibit built-in or library-provided edit distance functions? If not then the averages you link are not especially relevant: PHP handily wins the existing edit distance question by virtue of its built-in function. – Peter Taylor Jun 25 '13 at 20:27
• (That existing question does also raise the possibility of yours being closed for not being sufficiently different). – Peter Taylor Jun 25 '13 at 20:28

# Fastest Code: checking if interval pairs overlap

Given an unsorted input of many interval pairs (50+), write the fastest algorithm to determine if they do not overlap.

An interval pair is said to overlap if interval x and interval y are overlapping.

Example input 1:
interval x , interval y

10-25, 50-60
10-15, 25-60


Output:
Can be in any true false format.

false (They overlap)


reasoning:

a.x overlaps b.x
a.y overlaps b.y


Example input 2:

10-25, 50-60
20-30, 25-30


Output:

true (they do not overlap)


reasoning:

a.x overlaps b.x
a.y does not overlap b.y


Scoring:

[not sure...]
brute force gives a worst case n^2 runtime

• It's hard to understand what the program is supposed to do. It's better to give three separate self-contained test cases than to mix them together with extra identifiers which won't be in the actual input. But if I understand correctly, there's nothing difficult here at all. It's just interval overlap testing (two ifs) done twice for no obvious reason. – Peter Taylor Jul 5 '13 at 19:45
• The problem is that there will be a very large input. I'm thinking > 50 lines. – EAKAE Jul 5 '13 at 20:50
• I'm not sure whether or not to score it based on time, or worst case runtime. – EAKAE Jul 5 '13 at 20:59
• Instead of asking for overlap, ask for disjoint: "Check if a family of intervals is disjoint". I also think it would be more interesting if you give intervals in interval notation but I you should at least specify whether or not the endpoints are included. – Justin Dec 21 '13 at 7:41

Business Card Ray Tracer

I have no idea how to create a good code golf question!

See this description of a ray tracer with source code that fits on a business card. The author stopped when the code size was 1337 bytes.

http://fabiensanglard.net/rayTracing_back_of_business_card/index.php

Achieving identical output, optimise for minimum code size. Execution time is not relevant.

• I think what you have here is a straight ahead golf. All languages. You need only define the requirements. Do you want identical output or do you want "good output encompassing <list of features>"? – dmckee --- ex-moderator kitten Oct 6 '13 at 17:22
• For a minimum feature list I'd suggest something like (1) it is ray tracer (2) supports point-like lights and shadow + ambient light (3) supports mirrored (implies reflection) and matte surfaces (3) all objects are sphere and overlaps are allowed. With no requirement for (a) anti-aliasing; (2) finite sized light sources; (c) atmosphere effect or (d) depth of field; or (e) tiling and gradients. Notice however, that the example supports at least (b), (d) and (e). – dmckee --- ex-moderator kitten Oct 6 '13 at 17:29
• BTW--The one you linked can get a little bit more with #define Q return (R was already taken for the rand wrapper) and #define O operator. – dmckee --- ex-moderator kitten Oct 6 '13 at 17:33
• I suggest reading the Teapot question in the sandbox Mk IV and the comments - it's not the same question, but some of the same issues are relevant, and it might give you ideas for improvements to the spec. – Peter Taylor Oct 6 '13 at 22:48
• Yes. Read the teapot question for guidance. Ultimately I decided that one was too big, but we did get into some pertinent details. – luser droog Dec 1 '13 at 9:48
• This sandbox post has had little activity in a while and little positive reception from the community. Please improve / edit it or delete it to help us clean up the sandbox. – programmer5000 Jun 9 '17 at 15:32

# Countdown: Federal Holidays in the United States

Inspired by this question:

Christmas Countdown

Write a program or script that will countdown to the nearest U.S. federal holiday, at any given time, and will switch the display to an appropriate greeting during each holiday.

The following holidays must be tracked, and announced:

Holiday                         Date                    Greeting
==========================================================================================
New Year's Day                  Jan. 1                  Happy New Year!
Martin Luther King, Jr. Day     3rd Mon. in Jan.        Happy Martin Luther King, Jr. Day!
President's Day                 3rd Mon. in Feb.        Happy President's Day!
Memorial Day                    Last Mon. in May        Happy Memorial Day!
Independence Day                Jul. 4                  Happy Independence Day!
Labor Day                       First Mon. in Sept.     Happy Labor Day!
Columbus Day                    2nd Mon. in Oct.        Happy Columbus Day!
Veterans Day                    Nov. 11                 Happy Veterans Day!
Thanksgiving                    4th Thu. in Nov.        Happy Thanksgiving!
Christmas                       Dec. 25                 Merry Christmas!


The strings listed under "Holiday" and "Greeting" are all free. Shortcuts like "Merry X-mas!" or "Happy 4th of July" will count against you - the full and proper holiday names are free, so there's no good reason not to use them.

The following strings are also free, only when used as a label for time units or in advertising the next upcoming holiday:

days
hours
minutes
seconds
milliseconds
until
time


On any given non-holiday, the program must show a count-down timer which displays time remaining at least down to the second, and updates the display with an accurate value (according to the system clock) at least once per second. Time remaining until a holiday must be counted as the time until midnight (00:00:00) on that day.

How the days, hours, minutes, and seconds (and milliseconds, if you choose) are displayed is up to you, so long as all mandatory items are present and it is clear which numbers represent which value. Again, the strings defining units of time are free so there's no really good reason not to use them. (Though you won't be penalized for not using these strings, so long as it is still unambiguous which time units are which.) The program should also make apparent which holiday is being counted down towards.

On any given holiday, the program must cease displaying the countdown timer and instead display the appropriate greeting for that holiday from 00:00:00 until 23:59:59.

After a holiday is over, at 00:00:00 the next day, the holiday greeting must go away and be replaced with the countdown timer for the next holiday.

Answers must include:

• Name of language
• Score (length of golfed code, minus free characters)
• Golfed code
• Total length of golfed code
• Total number of free characters used
• Un-golfed code, with descriptive comments

The program must be capable of running accurately (according to the system clock) at any time, and must be able to run indefinitely. The only limitations to this should be those imposed by the host computer or the nature of the programming language.

Are there any additions/deletions/modifications that should be made to these rules?

I'm considering changing some of the greetings, but I'm not quite sure what to.

• "Happy Martin Luther King, Jr. Day!" is just a mouthful and feels awkward, but shortening it to "Happy MLK Day" feels weird too - any other suggestions?
• I'm not quite sure "Memorial Day" should really be preceded by "Happy" - thoughts?
• Any others?
• I think it would be more interesting if the strings were not free, but you still required exact match. I would like to see the compression scheme used by contestants. – John Dvorak Dec 7 '13 at 12:04
• @JanDvorak This is meant to be code-golf, not kolmogorov-complexity. – Iszi Dec 7 '13 at 22:11
• This challenge proposal has been inactive for over a month. I would like to take ownership of the challenge and make it ready for posting. Please let me know within the next 14 days if you have any objections and would still like to finish and post this challenge yourself. – user10766 Nov 3 '14 at 2:01

# Count unique characters in text.

Given a string for input, output the unique non-whitespace characters in that string along with a count of their occurrences. The list should be sorted in ascending order of ASCII code.

Examples

Input:

Hello, World!


Output:

Character    Count
!            1
,            1
H            1
W            1
d            1
e            1
l            3
o            2
r            1


Input:

The quick brown fox jumps over the lazy dog.


Output:

Character    Count
.            1
T            1
a            1
b            1
c            1
d            1
e            3
f            1
g            1
h            2
i            1
j            1
k            1
l            1
m            1
n            1
o            4
p            1
q            1
r            1
s            1
t            1
u            1
v            1
w            1
x            1
y            1
z            1


The actual formatting (headers, spacing, etc) of the on-screen output is up to you. The only conditions are that it must be sorted in ascending order by ASCII code, and it must be easy to tell what represents a character from the string and what represents a count of a given character. (For example, given a string of 99999999, the output should be explicit so that it is not confused as saying I have 9 8s.)

Ultimate challenge (taken from here):

JKqdJg+oJgiowgyIJgkS+gyxJdeS+gyxJ4yoJdybJdioJdqIJ4kS+KwFJ4QS+gzYJg+ow4vIJ4yxvd+IJgy=+dv=JdQx+gzbJrzx24zYJgkxJ4qLJKQxJ4yxJKqx+KqdJKqdJg+oJgiowgyIJgkS+gyxJdeo24yxJm+xJdybJdioJdqIJKi=J4wF+dvS+gzYJg+ow4zYJ4yxvdy=J4i=+Kv=JdQo+KqxJrzdJKzYJgkxJ4qLJgkxJ4yxJKvSJ4qbJKqdJg+oJgiowgyIJgkdJgyxJdeo24yxJm+xJdybJd+oJd+S+dz=J4wF+dvS+g+SJg+ow4vIJ4yxJ4voJgy=+dv=+dzdJgqxJrzdJKzYJgkS+dweJKQxJ4yxJKvSJ4qbJKq=24yYJgiowgyIJgkdJgzdJryo24yxJm+d24zxJd+oJdqIJ4kS+KwFJ4QS+gzYJ4y=2gzYJ4yxJ4voJgy=+dv=+dzdJgqxJrzx24zYJgkS+dweJKQxJ4fK+dQSJ4qbJKq=24yYJgiowgyIJgkS+gzdJryS+gyxJ4yoJdybJd+oJd+S+dz=J4wF+dvS+gzYJ4y=2gvIJ4yxJ4voJgy=+dv=JdQo+KqxJrzx24zY+dzS+dweJKQxJ4yxJKqx+KqbJKq=24vbJdyowgyIJgkdJgzdJryS+gyxJm+d24zxJdioJd+S+dz=J4wF+dvS+gzYJg+ow4vIJ4yxJ4voJgy=+Kv=JdQx+gzbJrzx24zYJgkS+dweJgkxJ4yxJKvSJ4qdJKq=24yYJgiowgyIJgkdJgzdJryS+gyxJ4yoJdybJd+oJdqIJKi=J4wF+dvS+gzYJg+ow4vIJ4yxJ4v=J4i=+Kv=+dzdJgqxJrzx24zYJgkS+dweJgkxJ4fKJ4qx+KqdJKqdJg+SJdyowg+oJgkS+gyxJdeS+gyxJ4yoJdybJd+oJdqIJ4kS+KwFJ4QS+g+SJ4y=2gzYJ4yxJ4v=J4i=+Kv=JdQo+KqxJrzx24zY+dzS+dweJKQxJ4yxJKvSJ4qbJKqdJg+oJgiowg+oJgkS+gzdJryo24yxJ4yoJdybJdioJdqIJ4kS+KwFJ4QS+g+SJg+ow4vIJ4yxvd+IJgy=+dv=JdQo+KqxJrzdJKzY+dzxJ4qLJKQxJ4yxJKqx+KqdJKq=24vbJdyowg+oJgkS+gzdJryo24yxJ4yoJdybJdioJd+S+dz=J4wFJ4QS+gzYJg+ow4zYJ4yxvd+IJgy=+Kv=+dzdJgqxJrzdJKzYJgkxJ4qLJgkxJ4yxJKvSJ4qbJKq=24vbJdyowgyIJgkdJgyxJdeo24yxJm+xJdybJd+oJdqIJKi=J4wF+dvS+g+SJ4y=2gvIJ4yxvd+IJgy=+dv=+dzdJKzbJrzdJKzY+dzS+dweJgkxJ4yxJKvSJ4qbJKq=24yYJgiowg+oJgkS+gyxJdeo24yxJ4yoJKzxJd+oJdqIJKi=J4wF+dvS+gzYJg+ow4vIJ4yxJ4v=J4i=+dv=+dzdJgqxJrzx24zYJgkxJ4qLJKQxJ4fKJ4qx+KqdJKqdJg+oJgiowgyIJgkS+gzdJryS+gyxJm+d24zxJd+oJdqIJKi=J4wFJ4QS+gzYJ4y=2gzYJ4yxvdy=J4i=+Kv=+dzdJKzbJrzx24zY+dzxJ4qLJKQxJ4yxJKqx+KqdJKqdJg+SJdyowg+oJgkdJgzdJryo24yxJm+d24zxJd+5


• This isn't really an interesting problem. The shortest answer is almost certainly going to be fewer than 10 characters. – Peter Taylor Dec 11 '13 at 12:19
• @PeterTaylor While I mostly agree with your comment - already the header line may contain more than 10 characters. – Howard Dec 12 '13 at 6:15
• "The quick brown fox jumps over the lazy dog." contains "e" three times. – Howard Dec 12 '13 at 6:16
• @Howard Thanks. I must be blind - it took me about five times of reading your comment to find it. Also, do remember that the header is optional to a certain degree - you just need to make sure the output is unambiguous as to which items are characters from the string, and which are character counts. – Iszi Dec 12 '13 at 7:02
• My brain instantly went into bash mode. wc and uniq practically solve half of this, but not in any particularly short manner. – Rob Dec 17 '13 at 20:31

# Quine with syntax highlighting

I don't really have much of an idea how to properly pose a quine challenge, or what the common syntax highlighting rules are (or aren't) for various languages. So, I figured I'd just toss this concept up here for consideration and let the community flesh it out if they think it's a good idea.

• I'm pretty sure some languages don't even have syntax to highlight – John Dvorak Dec 13 '13 at 20:12
• @JanDvorak Perhaps this would not quite be an "all languages" challenge, then - only languages which naturally lend themselves to syntax highlighting would be eligible. – Iszi Dec 13 '13 at 20:19
• You also can't use a language that cannot render any decent GUI. Also, specifying the amount of syntax highlighting the program needs to generate will be hell. – John Dvorak Dec 13 '13 at 20:36
• I don't think this question is feasible, due to the output restrictions and due to the difficulty in defining the minimum required syntax highlighting. – John Dvorak Dec 13 '13 at 21:09
• I like this idea. I think you could specify an adequate level of highlighting with just keywords, strings or characters and numeric literals each having their own color. – Οurous Feb 28 '18 at 21:13

### PETSCII banner

In an other world... I was using a PET 2001 who used some particular PETSCII charset.

The screen green on black, with 40 columns and 25 lines, was only able to display characters from this charset. No way to draw dots or lines...

But in the chaset, there is some ▝ and ▚, which, ( by the use of reverse video in order to obtain 16 chars: ' ','▖','▗','▘','▝','▀','▄','▐','▌','▞','▚','▟','▛','▜','▙','█' ) make us able to draw graphics on a 80x50 dots plan.

Using an internal clock triggering IRQ, I've done a animated prompter like this:

The goal of this is to make a similar banner, with same charset, (but using UTF-8 characters: ' ','▖','▗','▘','▝','▀','▄','▐','▌','▞','▚','▟','▛','▜','▙','█'). Warn, this charset use inverted lower/upper cases.

• This imply the use of PETSCII charset, I will post them there as a json string, before getting this out of the sandbox if some interest...

• The tool have to change his position 20 time per second.

• The tool must accept as argument, the string to display.

• The tool must add date and time in the form - WDay MDay Mnth Year, HH:MM:SS -

• Scrolling have to be done bit per bit: I.E.: by half character!

• Shortest code...
• -3 if size of console is not limited to 40 columns
• -5 if cpu usage stay less than 90% (On my poor Core(TM)2 Duo CPU E8400 @ 3.00GHz, with 4G ram)
• -5+ if cpu usage stay less than 50%
• -5+ if cpu usage stay under 5%

C.U.

• as for the CPU bonuses - what is the target environment, what is the smoothing factor, and what processes count against this measure? – John Dvorak Dec 15 '13 at 6:19
• This sandbox post has had little activity in a while and little positive reception from the community. Please improve / edit it or delete it to help us clean up the sandbox. – programmer5000 Jun 9 '17 at 15:32

# McDonald's Drive-Thru

Changes from original:

• Provided some clarification of requirements with regards to impossible ordering quantities.
• Added specification to include total cost of order.
• Added specification to prefer lowest cost in case of a tie for number of packages.

TODO:

• Verify package sizes and pricing to be used for this challenge.
• Add pricing to output samples.
• Edit or remove "not have any limitations" rule. As currently written, it may force otherwise unnecessary bloating of code in some languages. (e.g.: PowerShell can handle numbers as uint64 to work with extremely large quantities, but it defaults to int32.)

We want to write a program to help McDonald's Drive-Thru employees assist their customers in ordering Chicken McNuggets. Chicken McNuggets only come in packs of 4, 6, 9, or 20. However, customers may not always be considering this when they pull up to the speaker.

For example, a customer might want to order 50 McNuggets but they really don't care what sort of packaging they come in - they just want to make sure they get 50 McNuggets one way or another. We want to help the customers get the best value out of their order - that is, to compose an order large enough to accommodate their needs in as few packages as possible with little to no excess.

Users will provide a request for n Chicken McNuggets. Your program's task is to provide the user with the sizes and numbers of McNugget packages needed to fulfill the order exactly. If the exact order cannot be fulfilled, the system must output an order which would meet the customer's needs with as little excess as possible. The system must also provide the total cost of the order.

## Rules

• For values of n which can be ordered exactly, output how many of each pack must be ordered to achieve the requested quantity.
• For impossible orders (1,2,3,5,7,11), print "[requested quantity] is impossible. Have [nearest valid quantity >n]:" followed by the normal output for the nearest possible quantity >n.
• Impossible orders cannot be hard-coded. The program must be able to determine whether fulfilling an order exactly is possible without being explicitly told that 1,2,3,5,7, and 11 are impossible.
• Output must exclude any package sizes which do not need to be ordered.
• Output must be in descending order of package size.
• Output must include the sum total cost of all the packages. (Tax not included.)
• Further layout and formatting of the output is up to you, so long as it is unambiguous.
• Program must not have any limitations beyond those inherent to the system or programming language.
• If there are multiple ways to assemble the order in the least number of packages, output the method which has the lowest total price.

Examples:

Input: 8
Output:

2x4


Input: 43
Output:

1x20 1x9 1x6 2x4


Input: 11
Output:

11 is impossible. Have 12: 2x6


Relevant Numberphile Link

My main concern is that this problem may be too similar to this thread:

Work out change

Otherwise, are there any changes that should be made to this?

• My recommendation is to minimize the total cost of the order, rather than the number of packages. Based on these prices: fastfoodmenuprices.com/mcdonalds-prices, the costs are $2.99,$3.89, $4.29, and$5.00. This website lists the "9 piece" as "10 piece", I think that might be an error. – PhiNotPi Dec 14 '13 at 0:01
• Why the restriction #3? – John Dvorak Dec 14 '13 at 6:12
• I agree that it's too similar to the existing question. In addition, "nearest valid quantity" isn't unique, and you don't give any hint as to how to break ties. – Peter Taylor Dec 14 '13 at 10:17
• @PeterTaylor Tiebreaker is specified as ">n", where "n" is the quantity requested by the user - that is, we want to give the user an option that will have at least as many nuggets as they want to order. – Iszi Dec 14 '13 at 23:37
• @JanDvorak Essentially, to up the difficulty a notch. I figure it's a little trickier to catch the invalid quantities in the process of figuring out the answer if you can't write a simple if statement to match against the known quantities. – Iszi Dec 14 '13 at 23:42
• @PhiNotPi Not sure if that's an error on the site, or a regional difference. The information I posted was based on the linked Numberphile video, which was made in the U.K.. It's also possible they may have changed the menu since then. Presuming that larger packages hold better value in terms of cost-per-nugget than smaller ones, the problem as stated should work itself out to the same goal as you've suggested. However, it might help to differentiate the challenge from the suggested duplicate if we add the total price into the expected output. – Iszi Dec 14 '13 at 23:45
• My question is: how are you going to measure that? How large part of this knowledge are we disallowed from encoding? Can we memorize all but one? Can we special-case 1,2,3? Or, is it that anything goes as long as it either can be generalised to other Frobenius problems, or is inclusive, not exclusive? – John Dvorak Dec 14 '13 at 23:47
• @JanDvorak The program should be able to work out for itself whether or not a given quantity is invalid - that's all there is to it. By its nature, I suppose that means solutions would be able to also handle other Frobenius problems. In fact, I was actually considering a separate "return the largest impossible quantity" problem, where users input several integers and the program outputs the largest quantity that cannot be achieved by adding multiples of those integers. – Iszi Dec 14 '13 at 23:53
• Provided some updates to address comments. – Iszi Dec 15 '13 at 2:34
• @Iszi Minimizing cost should serve as a tiebreaker for when there are multiple solutions with the minimum packaging. For example, look at N=36. The solution {0*4,0*6,4*9,0*20} works, but {1*4,2*6,0*9,1*20} is cheaper. (I used the costs {{4,2.99},{6,3.89},{9,4.29},{20,5.00}}) – PhiNotPi Dec 15 '13 at 3:07
• @PhiNotPi Ah, I think I misunderstood when Peter said there wasn't a specifier for the tiebreaker. For some reason, I was thinking it was not possible for there to be a tie of that sort. Adding the price aspect definitely helps sort that out, then. Thanks. – Iszi Dec 15 '13 at 3:15
• FWIW, it was my misreading. I failed to see the ">n". – Peter Taylor Dec 21 '13 at 12:01

## 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

Since this question is closed, I figured I'd post it here so further issues can be hammered out in Meta instead of the main site.

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>
<head>
<title>Job Application</title>
</head>
<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="text" name="answer" value="" />
<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>
<head>
<title>Job Application</title>
</head>
<body>
<p>Well done, that was the correct answer. Now email your source
code to jobs@example.com with the following text in the Subject
header:</p>
<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. – squeamish ossifrage 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. – squeamish ossifrage 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

This is my first try at writing a challenge. Please let me know how I can improve it.

# Roman Calculator

Create a basic calculator for Roman numerals.

### Requirements

• Supports +,-,*,/
• Input and output should expect only one prefix per symbol (i.e. 3 can't be IIV because there is two I's before V)
• Input and output should be left to right in order of value, starting with the largest (i.e. 19 = XIX not IXX, 10 is larger than 9)
• Left to right, no operator precedence, as if you were using a hand calculator.
• Supports whole positive numbers input/output between 1-4999 (no need for V̅)
• No libraries that do roman numeral conversion for you

### For you to decide

• Case sensitivity
• Spaces or no spaces on input
• What happens if you get a decimal output. Truncate, no answer, error, etc..
• What to do for output that you can't handle. Negatives or numbers to large to be printed.

### Extra Credit

• -20 - Handle up to 99999 or larger (numbers with a vinculum)

Sample input/output

XIX + LXXX                 (19+80)
XCIX

XCIX + I / L * D + IV      (99+1/50*500+7)
MIV


The shortest code wins.

• You might want to be explicit about which variants of Roman numerals need to be supported. For example, do I have to understand IV as 4, or can I require that it be written as IIII? And what about, say, writing 8 as IIX instead of VIII, 19 as IXX or XVIV instead of XIX, or 99 as IC instead of XCIX? (All these variants have, AFAIK, been used classically.) – Ilmari Karonen Feb 9 '14 at 22:36
• @IlmariKaronen thanks. I modified the question to be slightly more specific about that. – Danny Feb 10 '14 at 14:09
• I think that using IV, IX, IC, XC, etc. should be alright, but only allow one prefix. Also, 19 should be written XIX, not IXX. One other thing, can we assume that the operators will be separated by a space, or no? – user10766 Feb 12 '14 at 0:32
• 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:06
• 1. I don't need to handle I/III but need to handle I/III+II/III? 2. For the extra can I output maybe [V] for 5000? – l4m2 Apr 12 '18 at 15:05
• @programmer5000 it was posted to main awhile ago. codegolf.stackexchange.com/questions/20670/… – Danny Apr 26 '18 at 11:58

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

## Golf a random Human Genome fragment with non-random features

A totally random genome fragment is easy enough: just spit out the letters ATCG in random order, and you're done. So let's try something a little less random and more useful to science.

Your program will:

• Accept an argument from the user for number of base pairs (20bp-10000bp must be supported, more if you wish)
• Accept an argument from the user for GC content. This indicates how frequently the generated sequence should contain the G and C bases as a percentage of total sequence length.
• Include at least one complete gene in every request of 500bp or more, where a gene is defined as an otherwise random sequence that begins with a start codon triplet (ATG) and ends with the first stop codon triplet it encounters (TAG, TGA, or TAA). The distance between the start codon and the stop codon does not have to be a multiple of 3.
• Vary gene content (the portion of the fragment that is "gene", inclusive of the gene's start and stop codons) linearly with respect to GC content (when sequence >= 500bp). At the extremes, when GC content is 0%, gene content is 10%; when GC content is 100%, gene content is 60%.
• Output a single-strand sequence that complies with the above specs and the user's given parameters. (i.e. a single row of letters will suffice since it is trivial to deduce the complementary strand of the DNA given the sequence of one strand)
• Calculate the actual GC content %, actual number of genes, and actual gene content % in the resulting fragment, and output a status line below the sequence conforming to the example format below. Percentages may be rounded to one decimal place. Actual values may deviate by +/- 3% from the expected outcome based on user's input.

GC content: 42.1% | Genes: 3 | Gene content: 32.1%

Your program will not:

• Use any Internet, library, or built-in gene sequence generation functions or databases. Roll your own.

Sufficient randomness:

• For the purposes of this challenge, any built-in random/pseudo-random number generator function, GUID generator, well-seeded cryptographic hash function, etc. is considered an acceptable source of randomness.

What-ifs:

• What if another start codon occurs before the stop codon? E.g. ATGXXXATGXXXXXXXXXXXXTAG. This is acceptable, but the "gene" length in this case is calculated from the most proximal start codon to the stop codon.
• What if another stop codon occurs after a stop codon? E.g. ATGXXXXXXXXXXXXXTAGXXXXXXTAG This is also acceptable, but likewise the "gene" length is calculated from the start to the most proximal stop.
• What if both of these things happen? E.g. ATGXXXATGXXXXXXXXXXXXTAGXXXTGA. Here again, the "most proximal" principle applies and the gene content is demarcated by the innermost start and the innermost stop.
• Do "orphaned" start and stop codons that do not demarcate a gene count as gene content? No.

This challenge is code golf, so shortest valid code wins.

Post example output from a 500-bp request with GC content between 35% and 65%, and have fun!

• "Use hardcoded fragments for anything other than the start and stop codons." - why not? Specifying criteria for what counts as enough randomness should make these useless in any case. Speaking of which, you need to specify criteria for what counts as enough randomness. – John Dvorak Feb 28 '14 at 5:54
• The only partial output example given flagrantly violates the spec. If the GC content is 42.1%, the gene content should be 31.05%, not 22.0%. The definition of "gene" is also imprecise: in the sequence AUGCCAUGCCUAGCUAA, which is the gene? – Peter Taylor Feb 28 '14 at 12:02
• @PeterTaylor AUG starts the gene, then come the CCA, UGC, CUA and GCU triplets, none of which terminate the gene. Now if there were three C's instead of two, then UAA would be the terminating triplet and the whole sequence would form a gene. I agree the definition is imprecise, though. – John Dvorak Feb 28 '14 at 12:11
• @JanDvorak, (part of) the point of that example is that there are two AUG substrings. – Peter Taylor Feb 28 '14 at 12:30
• Good points. I was hoping to avoid having too much text, but that came at the expense of less clarity than the challenge demands. Edit forthcoming. – Jonathan Van Matre Feb 28 '14 at 13:58
• Also, I've muddied the waters with RNA encoding and DNA encoding, (U vs T), which we can chalk up to a late night. – Jonathan Van Matre Feb 28 '14 at 14:00
• Revised accordingly, although I remain open to suggestions on how best to frame the standards for acceptable randomness. I want something that won't be exploited by answers making no effort at randomness, but that doesn't have the pain-in-the-butt factor of generating 10mb+ of data and running a Diehard test battery. – Jonathan Van Matre Feb 28 '14 at 17:20
• " This is acceptable, but the "gene" length in this case is calculated from the most proximal start codon to the stop codon. " - wait, what? In nature, the first one is the start codon, and the rest encode methionine. Under your scheme, methionine (which is an essential amino-acid) would be impossible to include into proteins. Your scheme would also be much harder to splice. Also, what happens to AUG substrings that are not triplet-aligned to previous AUG substrings? – John Dvorak Mar 1 '14 at 9:25
• In nature, the first ATG encodes the start of a protein coding region and defines a reading frame (triplet boundary), the rest encode methionine and the first triplet aligned stop codon encodes the end of the protein coding region (and no amino-acid). – John Dvorak Mar 1 '14 at 9:29
• As for the randomness, I'm not worried about the source of randomness (whatever native library is available is assumed to be good enough) but rather how the source of randomness is used (can we just start the sequence with a start codon and insert an end codon at just the right spot if it doesn't occur naturally sooner, then fill in with more random codons while avoiding ATG subsequences? Your "sufficient randomness" places constraints on the RNG (useless) but no constraints on how it's used (or that it needs to be used at all) – John Dvorak Mar 1 '14 at 9:34
• My true random number sequence generator was sitting there watching silently as I typed away the sequence ACACACACACACAC.... It's all okay. The TRNG was capable of producing something better - it just didn't really get to it. – John Dvorak Mar 1 '14 at 9:38
• In fact, the 3% tolerance for the CG content leaves no room for randomness when there are only 20 base pairs. I can shuffle the pairs and turn some A<->T or C<->G, but that's it. In fact, if the CG content is set to zero, the task is impossible: we want a gene content of 2 base pairs (which is itself impossible), but the start codon contains a G, and a single G in a 2bp sequence means a 5% CG content, 2% than is the limit. Not including a gene means that we are 7% under the gene content lower limit. Similarly, it's not possible to start or stop a gene with nothing but Cs and Gs. – John Dvorak Mar 1 '14 at 9:45
• Yeah, the 20bp starting point is a bad idea. The problem with start codons is that I considered introducing the idea of promoters and decided that would make the whole thing too complex. So in the absence of promoters there has to be some way to determine which Met is the start codon vs an amino acid and the easiest simplification is to have no Mets in the gene. Likewise, for "not triplet aligned", I'm trying to avoid having to go into explanations of frameshift mutations (even though a Frameshift% would be a cool parameter). – Jonathan Van Matre Mar 1 '14 at 14:29
• I am starting to think that all of these complexities should be included (this proposal stems from me noticing that most of the extant random DNA generators are pretty weak) and this should just be a popularity contest instead of a golf. Link a couple of good articles on the structure of the genetic code and let people add as many features as they wish. Making it a golf seems to be a catch-22 between too many compromises or a too-impenetrable wall of rules and conditions that will dissuade participation. – Jonathan Van Matre Mar 1 '14 at 14:33
• Perhaps a code-challenge where people earn x points for each complexity implemented? – user10766 Mar 2 '14 at 5:52

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

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

Further, we have a few restrictions:

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

Ok, people, what do you think about this question? Good? Bad? Leave a comment.

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

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

• I could say that people who post anti-creationist comments are just as annoying... – user10766 Mar 3 '14 at 3:35
• Are comments about creationism OK when they are replying to comments about extraterrestrial life? – John Dvorak Mar 3 '14 at 7:23
• Why no database access? Having to reimplement a database makes this challenge harder, but not more interesting. Speaking of which, code-golf requires hard criteria for accuracy (and absolute accuracy is impossible to achieve here). The usual solution is to use the popularity metric while telling people to strive for accuracy / accuracy and consciseness / accuracy and opacity / ... – 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

## DIM, the DIM Integer Machine

The DIM Integer Machine is an engine for producing integer sequences.

It has one major problem: To put it mildly, it's kind of...dim.

After producing a single number, it immediately forgets what sequence it was working on. The only thing it remembers is the last number it produced and the current direction of the search, either ascending or descending. (And of course, it remembers the methodology for finding numbers according to the commands it understands).

Consequently, the user is free to change their mind after each number by issuing a new command.

Suppose the DIM has just produced an integer square: 81

• User inputs P and submits the input.
• DIM understands that P is requesting the next prime number after 81
• DIM computes and returns 83.
• DIM forgets what it was doing.
• User inputs O.
• DIM understands that O is requesting the next odious number and returns 84.
• DIM forgets what it was doing.

The DIM functions only for numbers between 1 and 1,000,000. If the DIM reaches either extreme while performing a search it will reverse direction and continue searching.

(For example: If searching in ascending order for a prime when the last number was 999,999, it will encounter 1,000,000 which is not a prime, then switch to descending order and continue searching for the "next" prime by moving downward - 999,999...999,998, etc.)

The DIM remembers the last number as 1 when it is first activated for a searching session.

This is the full list of commands that the DIM understands:

• P - Next prime number
• S - Next square number
• F - Next Fibonacci number
• O - Next odious number
• W - Next wasteful number
• U - Next undulating number
• K - Next katadrome
• R - Reverse direction immediately; the next command will proceed in the new direction

Because the DIM is so...dim, it absolutely DOES NOT precompute lookup tables of numbers in these sequences. It is far too forgetful for that to work. The DIM also has no Internet connection, so it is unable to consult the Online Encyclopedia of Integer Sequences or other such sites. It also has a sense of pride, so it does not make use of built-in Fibonacci functions or NextPrime / PrimeIndex / PrimeTest type functions.

Given the parameters it knows - a starting number, a search direction, the type of number to find - it simply computes the next number by some means other than mere data retrieval.

The DIM may accept input interactively, or from a newline-terminated text file, or from a pre-initialized array. You may not pack extraneous data other than the command sequence into the input - play fair!

This is a code golf, so least number of bytes wins. Submit your program with output results for the following search sessions:

1. P O U R F O R U S O U R P R O W S
2. W O R K F O R P O O R F O R K S K O O P S R O O K S F O U R W O W S
3. P O O P O O P O O P P O O P P R O P S P R O W S P O R K S

It is assumed that you know what prime, square, and Fibonacci numbers are. A brief explanation of the other integer sequences follows.

Odious - a nonnegative number which has an odd number of 1s in its binary expansion. The first few odious numbers are 1, 2, 4, 7, 8, 11, 13, 14, 16, 19

Wasteful - a natural number that has fewer digits than the number of digits in its prime factorization (including the exponents). The first few are 4, 6, 8, 9, 12, 18, 20, 22

Undulating - has alternating digits of the form aba, abab, ababa, etc. Assume all U numbers are non-trivial, i.e. 3 digits or more. The first few: 101, 121, 131, 141, 151, 161, 171, 181, 191, 202, 212

Katadrome - A number whose hexadecimal digits are in strict descending order. The first few are 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 32, 33, 48, 49

• When I post the question, I'll also include external links to MathWorld or OEIS for those who need more detail on the less familiar sequences, but the explanations above should be sufficient for most, I think. – Jonathan Van Matre Mar 6 '14 at 23:28
• Your definition of "undulating" isn't the one I'm familiar with, which just requires that the digits alternately increase and decrease. Also, it would be better to include expected answers for the test cases, so that submitters can use them as test cases rather than them serving just for you to say "No, this is buggy". – Peter Taylor Mar 6 '14 at 23:57
• Yes, that's my plan, I just haven't finished double checking my results for the test cases yet. OEIS and Mathworld have the strict 2-digit definition of undulating, but I'll make sure to make the definition here more prominent so it is clear which interpretation is meant. – Jonathan Van Matre Mar 7 '14 at 0:04
• 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:09