# What is the Sandbox?

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

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

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

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

# Smuggle these Pincodes

After many years, our covert agent has managed to amass a list of all PIN codes in an enemy nation.

But there is a complication. The government of the country did become aware of our actions. Now our agent needs to smuggle the PINs past the customs without being caught!

Our spy needs help. Hiding a list of 10 000 codes will be too difficult. Luckily, our government can enlist the help of its loyal programmers (you!).

## The Challenge

Write a program that will output a list of all PIN codes from 0000 up to 9999 (inclusive). The program needs to be as short as possible to get past customs unnoticed.

### Rules

• The PINs must each be on a separate line.
• The program may not output anything other than the required output. However, it may output one (and no more than one) line end after the last PIN; e.g. 9999\n.
And, in case you were wondering:
• Depend on any external resources.
• Depend on having a specific file name.
• Take exceptionally long to run. If your program runs over a minute on an average home user’s computer, it’s invalid.
• Be written in a programming language for which there did not exist a publicly available compiler / interpreter before this challenge was posted.

### Scoring

The shortest code (in bytes, in any language) wins.

Any non-standard command-line arguments (arguments that aren’t normally required to run a script) count towards the total character count.

Your program’s output may deviate from the given list order, in which case your program’s byte count will incur a +10% penalty (rounded up).

• "You may assume your program won't receive invalid input." Why would it receive any input at all? What exactly is "valid" input here? – FireFly Nov 18 '14 at 22:52
• @FireFly I copied that line from a previous question without realizing that the program does not receive any input. I have removed it. – user2428118 Nov 18 '14 at 23:01
• Isn't this a bit trivial? It's just printing numbers from 0 to 9999 which are padded two 4 characters. Or printing the numbers from 10000 to 19999, ditching the leading 1, if you like. (Nothing against simple challenges, but I'm not sure how much room for optimisation this leaves.) – Martin Ender Nov 18 '14 at 23:03
• @MartinBüttner I realize it's a very simple challenge. I could not find any duplicates however, so I decided to put it in the sandbox anyway. But yes, there isn't much left to optimize, other than the things you mention and choosing the right programming language for the job. If there is consensus that it's too easy I can try to make it more challenging (or delete it). – user2428118 Nov 18 '14 at 23:15
• I think it's too easy. A golfer could write an optimal solution in 5 minutes. – xnor Nov 19 '14 at 8:17
• Easy questions give less experienced programmers another opportunity to participate. I'd still make it more challenging before you post it, but I don't think being easy is bad. – hmatt1 Nov 19 '14 at 16:46

# Preamble

Sometime in the early 21st century, computer scientists would discover the Hydra function (also known as the Lächerlich function), f, whose signature is given by

R = f( A, B, L, x, y, z )

where A, B, L, and R are finite integers, and x, y, and z are integers in the range [-231  231).

The function would quickly rise to preeminence due to the fact that it can perform 40 useful and well-known binary operations on A and B, returning the result in R. These operations are listed in the section "Operations" below, which provides a rigorous description of each.

It is important to note here that "integer" refers to the mathematical concept of an integer. In particular, there is no concept of integer overflow or of binary representation. In the case of variables A, B, and L, integer values are unbounded. In the case of x, y, z, the variables may not violate their explicit bound; any operation that could potentially assign an out-of-range value to these variables is an error and forbidden.

# Operations

The following code snippet defines all 40 (potential) operations of f. In each case, a name, description, and precise mathematical definition is provided. As a convenience, each operation also includes a C function that (notwithstanding data type bounds) implements the operation when compiled by gcc. In all cases, the mathematical definition should be considered authoritative.

<style>tr:nth-child(4n-3) td:first-child { width: 150px; font: bold 24px Times New Roman,Times,serif; }</style><style>tr:nth-child(4n-2) span { font-family: Courier New,monospace; }</style><style>tr:nth-child(4n) { font-family: Courier New,monospace; white-space:pre; }</style><style>tr:nth-child(4n) td { padding-bottom: 50px; }</style><script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.min.js"></script><div>Note that $$\left\lfloor\frac{A}{B}\right\rfloor _0$$ indicates "divide and truncate towards zero", and that $$\operatorname{sgn}\left( x\right)$$ indicates the signum function evaluated at $$x$$.<br><br>Also note that for operations conditionally returning $${\rm anything}$$, "anything" may be any value representable as an integer, or a fatal error. "Anything" does not have to be consistent from operation to operation. You may rely on the results returned for "anything" in subsequent calculations.</div><hr><br><br><div id="main">1. 0 [Constant 0] (0) $R = 0\cdot A + 0\cdot B$ {{return 0;}} 2. 1 [Constant 1] (1) $R = 1 + 0\cdot A + 0\cdot B$ {{return 1;}} 3. 2 [Constant 2] (2) $R = 2 + 0\cdot A + 0\cdot B$ {{return 2;}} 4. A [Value of A] (A) $R = A + 0\cdot B$ {{return A;}} 5. A + B [Sum of A and B] (sum) $R = A + B$ {{return A + B;}} 6. A - B [Difference of A and B] (diff) $R = A - B$ {{return A - B;}} 7. AB [Product of A and B] (prod) $R = AB$ {{return A*B;}} 8. A &#247; B [Truncated Quotient of A by B] (div) $R = \left\{ {\begin{array}{*{20}{l}}!!{\rm{anything}}&{{\rm{if\ }}B = 0} \\!!{\left\lfloor {\frac{A}{B}} \right\rfloor _0}&{{\rm{otherwise}}}!!\end{array}} \right.$ {{return A/B;}} 9. A &#247; B Remainder [Remainder after Division of A by B] (rem) $R = \left\{ {\begin{array}{*{20}{l}}!!{\rm{anything}}&{{\rm{if\ }}B = 0} \\!!{A - B\left\lfloor {\frac{A}{B}} \right\rfloor _0}&{{\rm{otherwise}}}!!\end{array}} \right.$ {{return A % B;}} 10. A modulo |B| [A Modulo |B|] (mod) $R = \left\{ {\begin{array}{*{20}{l}}!!{\rm{anything}}&{{\rm{if\ }}B = 0} \\!!{A\operatorname{mod} \left| B\right|}&{{\rm{otherwise}}}!!\end{array}} \right.$ {{   int X, Q;!!   X = B < 0 ? -B : B;!!   Q = A % X;!!   return Q < 0 ? Q + X : Q;}} 11. A = B [A Equals B] (is) $R = \left\{ {\begin{array}{*{20}{l}}!!{1}&{{\rm{if\ }}A = B} \\!!{0}&{{\rm{otherwise}}}!!\end{array}} \right.$ {{return A == B;}} 12. |A| > |B| [A is of Greater Magnitude than B] (gmag) $R = \left\{ {\begin{array}{*{20}{l}}!!{1}&{{\rm{if\ }}\left| A\right| > \left| B\right|} \\!!{0}&{{\rm{otherwise}}}!!\end{array}} \right.$ {{return (A > 0 ? A : -A) > (B > 0 ? B : -B);}} 13. A &and; B [Both A and B are Nonzero] (and) $R = \left\{ {\begin{array}{*{20}{l}}!!{1}&{{\rm{if\ }}\left( A \neq 0\right) \wedge \left( B \neq 0\right)} \\!!{0}&{{\rm{otherwise}}}!!\end{array}} \right.$ {{return A && B;}} 14. A &or; B [Either A or B is Nonzero] (or) $R = \left\{ {\begin{array}{*{20}{l}}!!{1}&{{\rm{if\ }}\left( A \neq 0\right) \vee \left( B \neq 0\right)} \\!!{0}&{{\rm{otherwise}}}!!\end{array}} \right.$ {{return A || B;}} 15. A &#8891; B [Either A or B is Nonzero, but Not Both] (xor) $R = \left\{ {\begin{array}{*{20}{l}}!!{1}&{{\rm{if\ }}\left( A \neq 0\right) \wedge \left( B = 0\right)} \\!!{1}&{{\rm{if\ }}\left( A = 0\right) \wedge \left( B \neq 0\right)} \\!!{0}&{{\rm{otherwise}}}!!\end{array}} \right.$ {{return (A != 0) ^ (B != 0);}} 16. A<sup>B</sup> [A to the Power of B] (pow) $R = \left\{ {\begin{array}{*{20}{l}}!!{A^B}&{{\rm{if\ }}B \geq 0\rm{\ or\ }\left| A\right| = 1} \\!!{0}&{{\rm{otherwise}}}!!\end{array}} \right.$ {{return (int)pow( A, B );}} 17. &#189;(A + B) [Average (Arithmetic Mean) of A and B] (avg) $R = \left\lfloor\frac{A + B}{2}\right\rfloor _0$ {{return (A + B)/2;}} 18. A<sup>2</sup> + B<sup>2</sup> [Sum of Squares of A and B] (sumsqs) $R = A^2 + B^2$ {{return A*A + B*B;}} 19. A<sup>2</sup> - B<sup>2</sup> [Difference of Squares of A and B] (diffsqs) $R = A^2 - B^2$ {{return A*A - B*B;}} 20. &#189;((-1)<sup>A</sup> - (-1)<sup>B</sup>) [Synchronicity of A and B] (sync) $R = \left( -1\right)^A - \left( -1\right)^B$ {{return (int)(pow( -1, A ) - pow( -1, B ));}} 21. |A + B| [Absolute Sum of A and B] (abssum) $R = \left| A + B\right|$ {{return A + B < 0 ? -(A + B) : (A + B);}} 22. |A - B| [Distance from A to B] (dist) $R = \left| A - B\right|$ {{return A < B ? (B - A) : (A - B);}} 23. max( A, B ) [Maximum of A and B] (max) $R = \max\left( A, B\right)$ {{return A > B ? A : B;}} 24. min( A, B ) [Minimum of A and B] (min) $R = \min\left( A, B\right)$ {{return A < B ? A : B;}} 25. minmod( A, B ) [Minmod Limiter] (minmod) $R = \left\{ {\begin{array}{*{20}{l}}!!{\min\left( A, B\right)}&{{\rm{if\ }}A > 0 {\rm\ and\ } B > 0} \\!!{\max\left( A, B\right)}&{{\rm{if\ }}A < 0 {\rm\ and\ } B < 0} \\!!{0}&{{\rm{otherwise}}}!!\end{array}} \right.$ {{   if( A > 0 && B > 0 )!!      return A < B ? A : B;!!   if( A < 0 && B < 0 )!!      return A > B ? A : B;!!   return 0;}} 26. A ? B : 0 [Return B Conditionally] (condb) $R = \left\{ {\begin{array}{*{20}{l}}!!{B}&{{\rm{if\ }}A \neq 0} \\!!{0}&{{\rm{otherwise}}}!!\end{array}} \right.$ {{return A ? B : 0;}} 27. &#189;(A + B)(|B - A| + 1) [Sum of Integers from A to B] (sumatob) $R = \frac{\left( A + B\right)\left( \left| B - A\right| + 1\right)}{2}$ {{return (A + B)*((B < A ? (A - B) : (B - A)) + 1)/2;}} 28. A <<<sub>2</sub> B [Left-shift A by B Zeroes in Binary] (rsh) $R = \left\{ {\begin{array}{*{20}{l}}!!{2^B A}&{{\rm{if\ }}B \geq 0} \\!!{\left\lfloor\frac{A}{2^{-B}}\right\rfloor _0}&{{\rm{otherwise}}}!!\end{array}} \right.$ {{return B >= 0 ? A*(1 << B) : A/(1 << -B);}} 29. A <<<sub>10</sub> B [Left-shift A by B Zeroes in Decimal] (rsh10) $R = \left\{ {\begin{array}{*{20}{l}}!!{10^B A}&{{\rm{if\ }}B \geq 0} \\!!{\left\lfloor\frac{A}{10^{-B}} \right\rfloor _0}&{{\rm{otherwise}}}!!\end{array}} \right.$ {{return (int)A*pow( 10, B );}} 30. A + sgn(B - A) [Increment A Towards B] (twrdb) $R = A + \operatorname{sgn}\left( B - A \right)$ {{return A + (B > A) - (B < A);}} 31. |A| sgn(B) [Magnitude of A with the Phase of B] (magphs) $R = \left| A\right|\operatorname{sgn}\left( B\right)$ {{return (A < 0 ? -A : A)*((B > 0) - (B < 0));}} 32. |A| > |B| ? A : B [Return Furthest From Zero: A or B] (ffzero) $R = \left\{ {\begin{array}{*{20}{l}}!! {A\rm{\ or\ }B}&{{\rm{if\ }}\left| A\right| = \left| B\right|} \\!!{A}&{{\rm{if\ }}\left| A\right| > \left| B\right|} \\!!{B}&{{\rm{otherwise}}}!!\end{array}} \right.$ {{return (A < 0 ? -A : A) > (B < 0 ? -B : B) ? A : B;}} 33. gcd( |A|, |B| ) [Greatest Common Denominator of A and B] (gcd) $R = \left\{ {\begin{array}{*{20}{l}}!!{\rm{anything}}&{{\rm{if\ }}A = 0\rm{\ or\ }B = 0} \\!!{\operatorname{gcd}\left( {\left| A\right| , \left| B\right|}\right)}&{{\rm{otherwise}}}!!\end{array}} \right.$ {{   int X, Y, T;!!   X = A < 0 ? -A : A;!!   Y = B < 0 ? -B : B;!!   while( Y != 0 ) {!!      T = Y;!!      Y = X % Y;!!      X := T;!!   }!!   return X;}} 34. lcm( |A|, |B| ) [Least Common Multiple of A and B] (lcm) $R = \left\{ {\begin{array}{*{20}{l}}!!{\rm{anything}}&{{\rm{if\ }}A = 0\rm{\ or\ }B = 0} \\!!{\frac{AB}{\operatorname{gcd}\left( {\left| A\right| , \left| B\right|}\right)}}&{{\rm{otherwise}}}!!\end{array}} \right.$ {{   int X, Y, T, P;!!   X = A < 0 ? -A : A;!!   Y = B < 0 ? -B : B;!!   P = X*Y;!!   while( Y != 0 ) {!!      T = Y;!!      Y = X % Y;!!      X := T;!!   }!!   return P/X;}} 35. A*B/(A + B) [Harmonic Mean of A and B] (harm) $R = \left\{ {\begin{array}{*{20}{l}}!!{\rm{anything}}&{{\rm{if\ }}A + B = 0} \\!!{\left\lfloor\frac{AB}{A + B}\right\rfloor _0}&{{\rm{otherwise}}}!!\end{array}} \right.$ {{return A*B/(A + B);}} 36. max(-|B|,min(|B|,A)) [Value of A Clipped to +/-|B|] (clip) $R = \max\left( -\left| B\right| , \min\left( \left| B\right| , A\right)\right)$ {{   int X;!!   X = B < 0 ? -B : B;!!   return A < -B ? -B : (A > B : B : A);}} 37. A|B| - B|A| [Commutator Bracket of A and B] (comm) $R = A\left| B\right| - B\left| A\right|$ {{return A*B < 0 ? (2*A*B*((B > 0) - (B < 0))) : 0;}} 38. |A| mod 10 = |B| mod 10 [A and B Have Same Last Decimal Digit] (sameldd) $R = \left\{ {\begin{array}{*{20}{l}}!!{1}&{{\rm{if\ }}\left| A\right| = \left| B\right|\;\;\left(\operatorname{mod} 10\right)} \\!!{0}&{{\rm{otherwise}}}!!\end{array}} \right.$ {{   int X, Y;!!   X = A < 0 ? -A : A;!!   Y = B < 0 ? -B : B;!!   return X % 10 == Y % 10;}} 39. (A<sup>B</sup> - 1)/(A - 1) [Sum of First B Terms in Power Series 1 + A + A<sup>2</sup> + ...] (pwrsrs) $R = \left\{ {\begin{array}{*{20}{l}}!!{\rm{anything}}&{{\rm{if\ }}B < 0} \\!!{\rm{anything}}&{{\rm{if\ }}A \leq 1} \\!!{\frac{A^B - 1}{A - 1}}&{{\rm{otherwise}}}!!\end{array}} \right.$ {{return (int)(pow( A, B ) - 1)/(A - 1);}} 40. B<sup>2</sup>/(A<sup>2</sup> + 1) [Squared Distance of the Line Ax + B to the Origin] (sqdist2orgn) $R = \frac{B^2}{A^2 + 1}$ {{return B*B/(A*A + 1);}}</div><script type="text/javascript">$('#main').html( '<table>' +$('#main').html().replace( /([^$]+) \[(.+?)$ $$(.+?)$$ \\$(.+?)\\$ \{\{(.+?)\}\}/g, '<tr><td>$1</td></tr><tr><td>$2 (<span>$3</span>)</td></tr><tr><td>\$4\$</td></tr><tr><td>$5</td></tr>' ).replace( /!!/g, "\n" ) + '</table>' );</script><script type="text/x-mathjax-config;executed=true">MathJax.Hub.Config( { "HTML-CSS": { preferredFont: "TeX", availableFonts: ["STIX","TeX"], linebreaks: { automatic: true }, EqnChunk: (MathJax.Hub.Browser.isMobile ? 10 : 50) }, tex2jax: { inlineMath: [ ["$", "$"], ["\\\$$","\\\$$"] ], displayMath: [ ["$$","$$"],["\$", "\$"] ], processEscapes: true, ignoreClass: "tex2jax_ignore|dno" }, TeX: { noUndefined: { attributes: { mathcolor: "red", mathbackground: "#FFEEEE", mathsize: "90%" }}, Macros: { href: "{}" } }, messageStyle: "none" } );</script><script src="//cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_HTML-full"></script>

# The Nature of f

The properties of f are summarized as follows:

• The operations in f are purchased with operation points (OP) and branching points (BP). f is implemented using no more than 120 OP and no more than 20 BP.

OP and BP purchases costs apply once per code element purchased. For example, the code

while( A > 0 )
A = A - B;

incurs the costs of one while loop, one condition, one assignment, and one binary operation, even if the condition, assignment, and binary operation may be evaluated more than once.

• No unary operations are permitted.

• Constant conditions (e.g. true, false, or equivalent) are permitted. All non-constant conditions must be explicit (e.g. no if( A )).

• Only the binary operations and conditions listed under "Binary Operations and Conditions" are permitted.

• The ternary operation <condition> ? <iftrue> : <iffalse> is permitted at the cost of 1 BP plus any cost(s) associated with the operands. Languages that don't explicitly support this ternary operation may implement it as a function.

• f must return a result in worst case O(log max(|A|,|B|)) time or better.

• f may recursively invoke itself at a cost of either 1 BP or 2 OP, but only to a worst case stack depth of O(log max(|A|,|B|)) or better.

• The following control structures are permitted in f:

• if blocks cost 1 BP each plus the cost of the branch condition
• if else blocks cost 2 BP each plus the cost of the branch condition
• if elseif blocks cost 1 BP per if, elseif, or else, plus the cost(s) of any branch conditions
• while loops and for loops cost 2 BP each plus the cost(s) of any initialization, loop condition, and loop update statements
• do while loops cost 1 BP each plus the cost of the loop condition
• goto, break, named break, continue, and named continue statements cost 1 BP each
• return statements cost 1 BP each, with the exception of the last top-level return that appears in f, which costs nothing

Programming languages that do not support the above structures may implement them as separate functions/methods/closures or as semantically equivalent code. For example, the code

while( 1 ) {
<statement>
...
if( A == B )
break;
}

is semantically equivalent to the code

do {
<statement>
...
} while( A != B )

and hence the former may be used at the cost of 1 BP (the cost of a do while loop).

# Variables and Data Types

Variables and data types in f are summarized as follows:

• No variables may be defined or used by f except for the parameters A, B, L, x, y, z, which may be both read and assigned. Variable assignments may not be chained or nested in expressions (e.g. A = B = 0, w = y == 1 || (z = 10) are not permitted). If a programming language does not support assignment to parameters, parameters may alternatively be copied into proxy local variables at the start of the function. Once this is done, the original parameters may not be referenced.

• Variable assignment incurs no OP or BP costs.

• Assignment to x, y, and z must respect the strict bounds on these variables. For example, if A is not guaranteed to be bounded by [-231  231), the assignment x = A is an error and illegal, even if a programming language would ordinarily allow it. The assignment x = A % 2 (with the semantics of the % operator defined below) is legal since all values of A are guaranteed to yield a legal value of x.

Note that these same restrictions apply when passing arguments to recursive invocations of f.

• It is recommended that A, B, L, x, y, z all be represented using the same type, but this is not a requirement. Implicit casts, explicit casts, method calls, and/or explicit function calls for converting between data types are allowed in all contexts, provided that both:

• no clipping, truncation, or wraparound occurs as a result of the conversion
• all operations on all data types are homomorphic to operations on the integers (notwithstanding the limited range of x, y, and z)
• Constants may be defined at no cost, but may only have values in the range [-231  231). Constants with values outside this range can be realized via binary operations (e.g. 123456789*987654321) but these operations incur costs as normal.

A constant may be defined using any data type and converted (implicitly or explicitly) to any data type so long as the conversion respects the rules listed above.

• A, B, L are ideally represented by a "big integer" type while x, y, z are best represented as big integers or signed 32-bit ints, but these are not requirements. In particular, an implementation of f may choose to represent all variables using bounded data types, which is allowable subject to two restrictions:

• under no circumstances may non-ideal effects such as clipping, truncation, floating point precision errors, etc. be used or exploited in the implementation of f
• any implementation of f relying on bounded data types that has these types replaced with unbounded counterparts must function properly over all inputs in this expanded domain

# Binary Operations and Conditions

Only the following set of binary operations and conditions may be used in the implementation of f. Each operation/condition has a cost of 1 OP. Operations/conditions may be implemented in any way (e.g. via infix operators, function calls, method calls, etc.) provided they are stateless and they conform exactly to the given definitions.

<style>tr:first-child { font: bold 18px Times New Roman,Times,serif; }</style><style>td { text-align:center; }</style><style>tr:nth-child(2n) { background-color:#eee; }</style><style>tr:not(:first-child) td:nth-child(3) { font-family: Courier New,monospace; white-space: pre; }</style><script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.min.js"></script><div id="main">addition $x + y$ {{x + y}} subtraction $x - y$ {{x - y}} multiplication $xy$ {{x*y}} integer division with truncation towards zero* $\left\lfloor\frac{x}{y}\right\rfloor _0$ {{x/y}} remainder of integer division* $x - y\left\lfloor\frac{x}{y}\right\rfloor _0$ {{x % y}} modulo** $x \operatorname{mod} \left| y\right|$ {{int k, q;!!k = y < 0 ? -y : y;!!q = x % k;!!return q < 0 ? q + k : q;}} binary left shift ${\begin{array}{*{20}{l}}!!{2^y x}&{{\rm{if\ }}y \geq 0} \\!!{\left\lfloor\frac{x}{2^{-y}} \right\rfloor _0}&{{\rm{otherwise}}}!!\end{array}}$ {{y >= 0 ? x*(1 << y) :!!   x/(1 << -y)}} binary right shift ${\begin{array}{*{20}{l}}!!{\left\lfloor\frac{x}{2^y} \right\rfloor _0}&{{\rm{if\ }}B \geq 0} \\!!{2^{-y} x}&{{\rm{otherwise}}}!!\end{array}}$ {{y >= 0 ? x/(1 << y) :!!   x*(1 << -y)}} logical AND ${\begin{array}{*{20}{l}}!!{1}&{{\rm{if\ }}\left( x \neq 0\right) \wedge \left( y \neq 0\right)} \\!!{0}&{{\rm{otherwise}}}\end{array}}$ {{x && y}} logical OR ${\begin{array}{*{20}{l}}!!{1}&{{\rm{if\ }}\left( x \neq 0\right) \vee \left( y \neq 0\right)} \\!!{0}&{{\rm{otherwise}}}\end{array}}$ {{x || y}} equality (Dirac delta) ${\begin{array}{*{20}{l}}!!{1}&{{\rm{if\ }}x = y} \\!!{0}&{{\rm{otherwise}}}\end{array}}$ {{x == y}} inequality ${\begin{array}{*{20}{l}}!!{1}&{{\rm{if\ }}x \neq y} \\!!{0}&{{\rm{otherwise}}}\end{array}}$ {{x != y}} less than ${\begin{array}{*{20}{l}}!!{1}&{{\rm{if\ }}x < y} \\!!{0}&{{\rm{otherwise}}}\end{array}}$ {{r < y}} greater than ${\begin{array}{*{20}{l}}!!{1}&{{\rm{if\ }}x > y} \\!!{0}&{{\rm{otherwise}}}\end{array}}$ {{x > y}} less than or equal to ${\begin{array}{*{20}{l}}!!{1}&{{\rm{if\ }}x \leq y} \\!!{0}&{{\rm{otherwise}}}\end{array}}$ {{x <= y}} greater than or equal to ${\begin{array}{*{20}{l}}!!{1}&{{\rm{if\ }}x \geq y} \\!!{0}&{{\rm{otherwise}}}\end{array}}$ {{x >= y}} bitwise AND of absolutes $\begin{array}{*{20}{l}}!!{\sum\limits_k {{x_k}{y_k}{2^k}} {\rm{\ given}}} \\!!{\,\,\,\,\,\,\,\left| x \right| = \sum\limits_k {{x_k}{2^k}} } \\!!{\,\,\,\,\,\,\,\left| y \right| = \sum\limits_k {{y_k}{2^k}} } \\!!{\,\,\,\,\,\,\,{x_k},{y_k} \in \left\{ {0,1} \right\}\,\,\forall \,k}!!\end{array}$ {{(x < 0 ? -x : x) &   !!(y < 0 ? -y : y)}}</div><hr><div>*division by zero is a fatal error<br>**modulo zero is a fatal error</div><script type="text/javascript">$('#main').html( '<table cellspacing="0"><tr><td>Operation</td><td>Definition</td><td>C Code (gcc)</td></tr>' +$('#main').html().replace( /([^$]+) \\\[(.+?)\\$ \{\{(.+?)\}\}/g, '<tr><td>$1</td><td>\$2\$</td><td>$3</td></tr>' ).replace( /!!/g, "\n" ) + '</table>' );</script><script type="text/x-mathjax-config;executed=true">MathJax.Hub.Config( { "HTML-CSS": { preferredFont: "TeX", availableFonts: ["STIX","TeX"], linebreaks: { automatic: true }, EqnChunk: (MathJax.Hub.Browser.isMobile ? 10 : 50) }, tex2jax: { inlineMath: [ ["$", "$"], ["\\\$$","\\\$$"] ], displayMath: [ ["$$","$$"],["\$", "\$"] ], processEscapes: true, ignoreClass: "tex2jax_ignore|dno" }, TeX: { noUndefined: { attributes: { mathcolor: "red", mathbackground: "#FFEEEE", mathsize: "90%" }}, Macros: { href: "{}" } }, messageStyle: "none" } );</script><script src="//cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_HTML-full"></script>

# Objective

Your objective is to write a function or a program containing a function that implements as many of the 40 operations of f as possible. When invoked at the top level, the arguments of f are assigned as follows:

• A and B specify the two general operands for the operation being selected. For any of the 40 listed operations where the result is not symmetric in A and B, you may return a result for swapped A and B if desired. For example, the function A + sgn(B - A) may alternatively return the value of B + sgn(A - B). Operations with swapped operands should be documented in your submission.

• L must always be zero when passed to the top level invocation of f. Recursive invocations of f may pass any legal value to L.

• x, y and z collectively specify the operation to be performed. This datum can be encoded any way you desire (respecting the limited range of these parameters). Your submission should include a list of at least one (x,y,z) tuple per implemented operation that causes f to compute the result for that operation. You may assume that only these tuples will be passed to a top level invocation of f, hence f may exhibit arbitrary behaviour (including errors and/or illegal operations) if undocumented tuples are passed to top level invocations.

As with L, recursive invocations of f may pass any legal values to x, y, and z. The results of any such intermediary operations need not be documented.

# Scoring

Scoring rules are as follows:

• If f does not implement all 40 operations, score 10 points per implemented operation plus 1 point per unused BP plus 1 point per unused OP.
• If f does implement all 40 operations, score 400 points plus 50 points per unused BP plus 25 points unused OP.

The highest scoring submission is the winner.

# Origami Code Golf

I like origami (especially unit origami), but lack the patience to actually complete a project.

Sounds like a wonderful job for a computer!

## Objective

Make a program or function that accepts a series of numbers (see next part) and outputs a folded version of a 1 x 1 square.

## Input

You will receive a list of numbers {a,b,c,d,e,f},{g,h,i,j,k,l}... (curly braces only added for clarity) Each set of numbers corresponds to 3 coordinates (a,b), (c,d) and (e,f). (a,b) and (c,d) each lie on the unit square (which also means that it is in the first quadrant). (e,f) lies within the unit square, but on a portion of the paper that is not on the line formed by (a,b) and (c,d).

(a,b) and (c,d) determine the line over which to fold the paper.

The portion of the paper that (e,f) lies in determines which side of the paper remains stationary during the fold. You may assume that this value will always lie on a portion of the square (e.g. not on a part of the square that is not there because of a fold).

For example, the input 0.5, 0, 0.5, 1, 0.25, 0.5 means that one should fold the paper in half over the vertical line at 0.5, with the left side remaining stationary.

Each fold (set of input numbers) is sequential, so one fold is made after another.

For example, if the previous example was followed by the input 0, 0.5, 1, 0.5, 0.75, 0.75, the paper should be folded over the horizontal line at 0.5, with the top part remaining stationary.

## Output

Your program or function must only output (graphically) the resulting shape and rotation of the folding. It is not required to output the correct location or size.

## Test Cases

input 0, 0.5, 1, 0.5, 0.5, 0.75 -

input 0, 0, 1, 1, 0.25, 0.5 -

input - 0.5, 1, 1, 0, 0.25, 0.5, 0, 0.25, 1, 0.25, 0.25, 0.75 -

input - 0.5, 0, 1, 0.5, 0.5, 0.5, 1, 0.5, 0.5, 1, 0.5, 0.5, 0.5, 1, 0, 0.5, 0.5, 0.5, 0, 0.5, 0.5, 0, 0.5, 0.5, 0, 0.25, 1, 0.25, 0.5, 0.5

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

• So all folds are valley folds? No mountain folds at all? You could add support for that by adding a command that flips the paper. Also, I don't think your resolution of the folding direction is unambiguous. Which way do I fold a fold that goes from the top left corner to the bottom right corner? And what coordinate system are you using? – Martin Ender Dec 7 '14 at 22:28
• I'm sorry, but all of that seems contradictory. If the origin is in the upper left, I assume that the y axis points down. In that case, the fold would be indicated by (0,0) to (1,1). This fold can occur bottom left to top right or vice versa. Your first rule says we should fold right, but the second rule says we should fold down. Therefore, I think this is ambiguous. – Martin Ender Dec 7 '14 at 22:36
• Hopefully this is better specified. (BTW, I was confused when you said top left to bottom right. That would have worked left to right/top to bottom. I see what you meant now). – Stretch Maniac Dec 8 '14 at 3:30
• "Your program or function must only output the resulting shape and rotation of the folding." In what format? Your examples show pictures, but it's not clear whether this is intended to be a graphical-output question or whether e.g. a list of vertices is acceptable. – Peter Taylor Dec 8 '14 at 9:59
• 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. – Nathan Merrill Apr 12 '15 at 19:05
• Feel free to post it yourself. I have no objections to your ownership. Good luck! – Stretch Maniac Apr 12 '15 at 19:31

## Phoneword generator

This is

### Goal

The goal is to write the shortest phoneword generator.

### Input

As input you get for just a sequence of numbers (0-9). Given via stdin.

### Output

You should write the first 15 possible results to stdout bonus points if the output only contains real words. The words need to have the exact same length like the input string.

What if there are less than 15 options?

Then you can just make up words.

### Phoneword

A phoneword, is a sequence of characters, that is typed with letters in your phone which map to the numbers they display.

How to treat 0 and 1

If the input contains a 0 or a 1, you should treat them as 0 and 1. To make a word with them anyway, you can use leetspeak.

### Mapping

For the mapping check this picture:

Taken from wikipedia

As example I use codegolf itself: 26334653 translates to CODEGOLF it also gives many more words, here is a list.

### Bonus

You can divide the amount of characters by 2, if your code gives only words which are in listed in the Oxford dictionary. For that you are allowed to use a web api to check them.

• Why is it a [restricted-source]? Are there any characters we cannot use in our code? – ProgramFOX Dec 29 '14 at 11:32
• Seems pretty similar to this question. The only difference seems to be that you require full matches. – Sp3000 Dec 29 '14 at 11:36
• @ProgramFOX Because I would like to ban languages that are mode for codegolf, I gonna add this. – Knerd Dec 29 '14 at 12:59
• @Knerd That isn't indicated by [restricted-source]; there isn't a tag for that. But why banning golfing languages? That doesn't seem fair to me. – ProgramFOX Dec 29 '14 at 13:02
• @Sp3000 I agree, that it is similar, but I still would see a difference in the questions themselves, because a) it needs an exact match and b) the 1 and 0 are valid ;) – Knerd Dec 29 '14 at 13:03
• @ProgramFOX I edited it a bit, check under rules. The main reason is, usually golfing languages win a contest, because they are made for that purpose. Which seems unfair for me towards other languages. – Knerd Dec 29 '14 at 13:06
• Then what does count as a "golfing language"? If you disallow them, there in my opinion should also be a clear definition of what exactly is disallowed. – ProgramFOX Dec 29 '14 at 13:18
• @ProgramFOX I think you are right. I'll go and remove that part. – Knerd Dec 29 '14 at 13:22
• It's not clear from the question what the input is, what the output is, what mapping between letters and digits you assume, what you mean by a word, or why it isn't a duplicate of the question which Sp3000 mentioned. – Peter Taylor Dec 29 '14 at 14:47
• @PeterTaylor I updated it a bit. – Knerd Dec 30 '14 at 14:52
• If there are less than 15 possibilities that are allowed by the Oxford dictionary, should the code output only the dictionary-approved possibilities, or make it up to 15 with other possibilities? – trichoplax Jan 3 '15 at 23:41
• The question as written doesn't specify whether 1 and 0 are valid in the input, and if they are, how they should be treated. – trichoplax Jan 3 '15 at 23:44
• @githubphagocyte check my edit :) – Knerd Jan 4 '15 at 14:45
• I would recommend phrasing Then you can just make up words more clearly. I'm guessing you mean that the remainder of the 15 possibilities do not need to use real words? – trichoplax Jan 4 '15 at 14:51
• To ensure everyone has the same interpretation of the rules, I would recommend clarifying what you mean by leetspeak. Does this mean 1 can be used as L and 0 can be used as O? Or can 1 only be used as i? Or either? – trichoplax Jan 4 '15 at 14:53

# Generate a Random Boolean Expression

In this challenge, you generate a random Boolean expression -- and then evaluate it.

## Input

Nothing, or a random seed if your program requires one.

## Output

A random Boolean expression and its value, formatted as a string

<expr> = <value>

The expression should be generated according to the following BNF grammar:

<expr> ::= "0" | "1"
| "(" <expr> "^" <expr> ")"
| "(" <expr> "v" <expr> ")"
| "(" <expr> ">" <expr> ")"
| "~" <expr>

Here, ^ stands for binary AND, v for binary OR, > for implication, and ~ for NOT. Whitespace is not significant. The correct value for the expression should be self-explanatory. Some correct outputs include

0 = 0
~ (~1 ^ 1) = 1
((1v1) ^ ~(0 >(1 ^ ~~~0))) = 0

## Detailed Rules

Assuming a perfect random number generator, your program must be able to generate any valid Boolean expression with nonzero probability (discounting whitespace). You must use you language's standard RNG, or one of higher quality.

You can write either a function or a full program, and a function can either return its result or print it to STDOUT. The fewest bytes wins, and standard loopholes are disallowed.

I'd like some input on whether this challenge is essentially similar to either this or this.

• The intro line talks about evaluating the expression, but none of the rest of the question does, and it seems to me that an approach which builds up the string and the value in parallel would meet spec. In that case, it's not a duplicate of the second question. It's borderline-duplicate of the first one, though. I probably wouldn't vote to close as a dupe, but I wouldn't put money on it staying open. – Peter Taylor Jan 15 '15 at 9:39

# Operator, i can't remember my phone number... code-challengequine

"Hello? Operator? How do i get my phone to tell me its own number?"

The challenge is to write a quine -- from your cellphone. Not a smartphone with a virtual keyboard, mind you. One of the old phones, where to get a 'c' you have to press 2 three times.

Because programmers are lazy, you want to do it in the least amount of keypresses.

A previous challenge (Calculate cell-phone keypresses) was to calculate the amount of keypresses it takes to produce a set of characters on a cellphone keyboard.

The challenge there wrote out all the keymappings well, so i'll just quote it here.

The keymaps are:

1:1
2:abcABC2
3:defDEF3
4:ghiGHI4
5:jklJKL5
6:mnoMNO6
7:pqrsPQRS7
8:tuvTUV8
9:wxyzWXYZ9
0:<space><newline>0

To type exaMPle TExt 01 , you would press 33 99 2 6666 77777 555 33 0 8888 33333 99 8 0 <a 1-sec pause here in real life but we'll ignore it>000 1 for a total of 37 keypresses.

The * key brings up a map of special characters:

.,'?!
"-()@
/:_;+
&%*=<
>£€$¥ ¤[]{} \~^¡¿ §#| with the first one (.) highlighted. You can move to highlight the required character using rectangular navigation keys and it takes another keypress to select. So to insert$, you would press *↓↓↓↓→→→<select> i.e. a total of 9 key-presses.

This means, that if you use a = 3 in your code, that is a (1), space (1), = (8), space (1), 3 (7), for a total of 18, even though it's only 5 bytes.

So as not to rule out languages/entries that use characters outside of this range, you can reach it with #, insert, special, select, {type the Unicode number of the character}, select for a total of 5 + Unicode #. I suppose you could use this trick to reduce the number of keypresses via *.

## Scoring

Your score is the number of keypresses used to type out the code. There is a Stack Snippet that you can use to calculate. It automatically picks the lower number if you could use either * or #.

The entry with the lowest score after 2 weeks wins!

• To facilate easy calculating of the score, i plan to include a snippet with the JS entry from the old challenge. – Scimonster Jan 22 '15 at 20:34
• While I think the scoring is a nice twist, I'm not a fan of reusing exactly the same challenge. This way, the scoring seems more like a gimmick than anything else. So I'd prefer if you used it for a different challenge (which may still be related to cellphone keys, just not exactly the same). Also, just a note, please don't actually tag it code-golf - the scoring is too different not to tag it code-challenge. – Martin Ender Jan 22 '15 at 20:35
• I actually thought of my challenge first, and only after went to see if it had already been asked. But if you think it's too similar, i'll try and think of a slightly different challenge. – Scimonster Jan 22 '15 at 20:37
• I redid the whole thing, what do you think of it now? – Scimonster Jan 25 '15 at 18:58
• I have an APL phone where every funny symbol has its own button. – feersum Jan 26 '15 at 9:01
• I like this scoring idea and definitely want to see a challenge based on it, even if it isn't a "quine" challenge. – PhiNotPi Feb 27 '15 at 4:09
• For once CJam wouldn't win – HEGX64 Apr 4 '15 at 10:32

# Find longest alphabet path (code-golf)

You are given a 2d array of size nxn that is filled with lowercasel letters a-z. Your goal is to find the longest continous path by only moving up/down/left/right. A path is a sequence of cells of the 2d grid, where the successor of the current cell must be a neighbour that is above, below, left or right. Also, each cell of the array can only be visited once per sequence. The value (the lowercase letter) of the successor must right before or after the one in the current cell (if the current cell has the value c, the successor must have value b or d).

# Output

You have to solve two tasks:

• The challenge stated above
• The challenge stated above plus another restriction: successors can only have the next letter in the alphabet, but not the previosu (if the current cell has the value c the successor must have the value d)

The output must consist of two n x n grids the same size as the input, each for one of the two tasks. The grids have to be the identical again, but all the unused cells that are not part of the longest sequence have to be set to a whitespace. If there are two or more longest sequences, only one arbitrary one of them has to be in the output.

# Testcases (more to be added)

Input:  Out1:  Out2:
ababa   ababa  ab
babab   babab
ababa   ababa
babab   babab
ababa   ababa

Input:  Out:  Out:
aba     aba   ab
aba
aba

abcd  abcd  abcd
hgfe  hgfe  hgfe
gfeb  gfeb
babc  babc
• This looks to me like a duplicate of codegolf.stackexchange.com/q/44922/194 – Peter Taylor Jan 28 '15 at 10:53
• Thanks, I didn't remember that challenge, but to me it seems different enough for a new challenge: On the one hand this challenge uses a 2d string instead of 1d on the other hand there is no restriction to words plus another output format needed. I think the overall ideas and needed approaches are quite different. Inspiration (i do not know what those puzzles are called genearlly) – flawr Jan 28 '15 at 10:59
• I see it as two versions of the longest path problem on sparse graphs with different graphs. – Peter Taylor Jan 28 '15 at 11:06
• Ok if you look at it like this, they are indeed the same problem, but I think the implementation will provide very different challenges. – flawr Jan 28 '15 at 11:14

# Logic Dots code-golfpuzzle-solver - Posted

• This wants the tag puzzle-solver. It isn't clear until really late that the shapes to place are all lines (or a by 1 rectangles, if you prefer): making that clear quite early would be useful. Without that context, the two 2s in the second example look like a requirement to place a 2x2 square. On my first read-through I took "they can also be vertical" to mean that some of the input shapes could be vertical: it wasn't until I saw the examples that I could reinterpret it as "You may rotate the shapes when placing them". – Peter Taylor Jan 27 '15 at 9:30
• @PeterTaylor fixed. – globby Jan 27 '15 at 15:48
• Posting test cases as an answer is a bad idea. To shorten the post, you could try putting the examples side by side, and you could use Stack Snippets. – Peter Taylor Jan 27 '15 at 22:45

# Hide your code in a Boggle board!

This proposal is intended to supersede my earlier proposal Find the Needle in the Haystack, of which I'm not convinced any more that it would work very well. I'll keep both proposals around for now, though.

## The Cops' Challenge

First, choose a program output, consisting of less than 100 printable ASCII characters (character code 0x20 to 0x7E, inclusive) - in particular the program must be written on a single line.
Next, you should write a number of programs (not necessarily in the same language), which all output that exact same string (including any trailing newlines) to STDOUT or closest alternative. Each of those programs should be made up of less than 100 printable ASCII characters, too.
Finally, design a Boggle board, which contains all of these programs. The Boggle board may contain as many unused character as you wish, but it has to be rectangular and all characters have to be in the printable ASCII range. See "Boggle Rules" below for how the Boggle board works.

You want the number of programs to be large, the board to be small and the programs to be hard to find.

None of the programs must take any input. You may print to STDOUT, a GUI dialog (as with JavaScript's alert()), or assume a REPL environment (like a browser console) - but if it's different from STDOUT, you need to state clearly where your output will go in each case.

Each program has to complete within 5 seconds on a reasonable machine. You are not allowed to use cryptographic methods, hashing functions, random seeds or string compression.

If your submission's boggle board is X characters wide, and Y characters tall, and you've hidden N programs in it, your submission's score is N3/(X*Y).

You should deliver:

• X, Y, N and your score.
• The languages of your N programs, including output destination if it differs from STDOUT.
• The Boggle board.
• The output of the programs.

An answer is cracked if N programs in the specified languages are found by a single robber (see The Robbers' Challenge below). If your answer has not been cracked for 7 days, you may claim immunity by revealing the programs in your answer (to prove that your answer was solvable).

The winner will be the immune submission with the highest score.

## The Robbers' Challenge

Every user has one attempt at cracking each submission. Your cracking attempt will be a list of programs found in a the submission's Boggle board. If your guess matches the description (all programs can be found according to the Boggle rules, all produce the correct output to the correct destination, and they are written in the required languages), and you are the first correct guess, then you get N*X*Y points. It is important to note that your programs do not have to exactly match the originals, as long as they meet the specification and can be found in the Boggle board. This means there could be more than one correct answer.

The robber with the most points wins. In the case of a tie, the robber who submitted fewer cracks wins.

Robbers should post their cracks as answers to the associated Robbers' thread.

## Boggle Rules

• To find a program in a Boggle board, you start at an arbitrary cell and add characters to the string by repeatedly moving to one of its neighbours.
• You may move one cell at a time, horizontally, vertically, or diagonally.
• No cell must be used more than once (within a single program or by multiple programs).

## Example

Consider this Boggle board as a cop submission:

1$int arun" !pts0 b "2K Along with the specification that the output is 20, and that there are 2 CJam programs, one Python 2 program and one Ruby program. A robber could now find: • K in the bottom right corner and 20 next to it as two valid CJam program. • print "20" as a valid Python 2 program: __i__ _r_n" _pt_0 _ "2_ • puts"20" as a valid Ruby program: _____ __u_" _pts0 __"2_ If no one cracked this, the cop's score would be 42/(5*4) = 0.8. If someone did crack this, that robber would get 4*5*4 = 80 points. ## Sandbox Notes • I intend to provide stack snippets which generate leaderboards for the cops and robbers. • The scores probably need some balancing. Suggestions? • I admit that the robbers' challenge is pretty similar to Calvin's Hobbies' recent challenge. This happened purely by accident - I was originally thinking about a word search C'n'R, which would have been too easily brute-forcible, so I changed it to a Boggle board. Of course, that doesn't matter when considering if it's a duplicate of course, but I think with hand-designed boards, looking for programs with fixed outputs in prescribed languages, makes this quite different and should hopefully make for a more balanced challenge. Furthermore, the cops' challenge of designing the boards is completely different. Please let me know if you disagree, though. • Should I allow cells to be reused within a single program? • I'd guess that allowing cells to be reused within a single program would make it much harder for a cop to prevent multiple unintended programs appearing in the board. – trichoplax Jan 24 '15 at 10:10 • I dislike the 'output any 100 printable ASCII characters rule' from the Unscramble challenge. It makes it too easy for cops, who can print out any stream of gibberish. It some languages, it is even possible for them to enter random characters without even knowing what the code does. – feersum Jan 26 '15 at 9:09 • @feersum I'm absolutely open to suggestions for better tasks. – Martin Ender Jan 26 '15 at 10:18 • How about recommend allowing cells to be reused (the whole fun of Boggle), but allowing one program per language? – Ypnypn Jan 29 '15 at 15:56 • @Ypnypn hm, sounds like a good idea. – Martin Ender Jan 29 '15 at 18:44 # Cursor Wars This question is based off of my previous Navigate Text with Arrow Keys golf. Here, a segment of text is the battle arena, and the opponents move like cursors. ## Idea 1: Tron / Light-Bikes As the cursors move left to right, they paint parts of the text. Neither cursor can move through a painted area. The cursor who runs out of moves first loses. To add a twist to the board's topology, I could make it so that the text area is flipped for the opponent. If I see the board: X----- --- ------Y Then the opponent sees the board: Y------ --- -----X With line-wrapping working differently for each player, they don't have the same movement patterns. ## Idea 2: Area Painting Like in the Tron idea, cursors paint an area. The cursor that paints the most area wins. I could make it make a few versions • Area painted once cannot be repainted: the winner is the cursor that painted the majority of area • Area can painted my moving right and cleared by moving left (backspacing). The winner is the one that painted the most area times time. (Each time step, players earn one point per painted area.) • Idea 3 (rather vague): Put actual characters on the board and have people collect them to form words or sentences (either as the winning criterion or to get some form of power-ups). This could still be based around a Tron idea, or characters could simply be used up (so that others can still travel there, but thy can't collect those characters again). – Martin Ender Feb 9 '15 at 16:37 # War of the Partitions You have been assigned 1000 men to your cause, and you must fight your opponent on 20 different battlefields simultaneously. You must decide how to split up your 1000 men into 20 ways. Furthermore, since the Nth battlefield is larger than the (N+1)th battlefield, the 20 partitions must be in non-increasing order. Each battlefield will have a skirmish. If you send more men than your opponent, you win that skirmish. Winning more skirmishes than your opponent across all battlefields scores you 1 Battle Point. You will then face every other opponent, where you will be allowed to reassign your men to another location. You have a large supply of necromancers that allow you to keep all of your men alive from battle to battle, so you may allocate all 1000 men every time you face another opponent. You will face each opponent 25 times. The player with the most Battle Points wins. # IO You will be passed a string of the history of the battles between you and your current opponent. Each line consists of a different battle. The choices will be space separated, and your opponent's choices will be listed first, separated by a comma. The following input: 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50,60 59 58 57 56 55 54 53 52 51 49 48 47 46 45 44 43 42 41 40 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50,51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 21 would represent two battles between a player. The first one would be a tie (each player won 10 skirmishes), while the second you won a Battle Point by winning 19 skirmishes. You must return a string containing a space separated list of integers. The total of all of the values must be 1000, and must be in decreasing order. • This game idea sounds very... familiar... but I don't see any KOTH based on it. Seems like a good idea. – PhiNotPi Feb 11 '15 at 23:38 • Maybe change decreasing to non-increasing to prevent ambiguity. – randomra Feb 14 '15 at 17:43 • Will the 25 battles be consecutive? It could be much quicker to save state (if allowed) than re-parse the whole history. (edit: file IO maybe slower, depends on the submissions and time limits) – randomra Feb 14 '15 at 17:49 • @rcrmn the two battling bots are side by side. The top line is the first battle, the second line is the second battle. – Nathan Merrill Feb 24 '15 at 14:24 • Sorry, I totally misread it! – rorlork Feb 24 '15 at 14:24 # Code File Header Do you have a large number of source files that you forgot to put a header on, but never bothered. Well then this challenge is for you! This is code golf, so shortest program that works wins. # The Challenge Write a function (if your language doesn't support this, write a program, that accepts a cmd line arg for the file name) that takes the name of a file then attaches to the top of that file a comments section stating the name of the author, the current date, and the file name, as comments in your language (if your language supports comments, if not then in C-Style/Doxygen). For instance, if your language was C/C++ the following must be appended at the top. using myself as the example. /** \author Henry Schmale * \date 2015-02-19 * \file [File Name] */ # Notes • You may subtract the length of your name from your submission. • Languages that don't support file I/O are not eligible for this code golf. • The date code should be in a human readable format, no unix time. Preferably in ISO format. • if your language supports multiple comment formats, you may use either or so long as the final result is the same, a documentation header on that file. • @MartinBüttner I did this before I learned how to use doxygen. – HSchmale Feb 19 '15 at 0:47 • What file name should be used if reading from stdin and writing to stdout? – Peter Taylor Feb 19 '15 at 12:21 • The spec regarding the file name is a bit confusing now. First you say "Write a function [...] that takes the name of a file then attaches to the top of that file [...] the file name" but then you say "Assume the file name is main.c". I think a simpler option would be to always take the file name as a command-line or function argument, but allow people to choose between STDIN/STDOUT, file I/O and another function parameter/return value for the actual file contents. – Martin Ender Feb 20 '15 at 9:26 • So why did you go back to disallowing languages without file system support now? :/ – Martin Ender Feb 21 '15 at 10:18 I'm only posting this in the sandbox because it may be too broad, even for a pop-con. If it gets some support I'll post it very soon. # Generating Postmodernist Writing and Other Logorrhea Postmodernist writings are known for dealing with highly abstract ideas, potentially in a verbose manner that may sound nonsensical to someone reading them. This type of writing is often called logorrhea, and is not limited to postmodernism. People have made programs that use natural language processing to generate realistic looking academic writings that are actually utter nonsense. One example is the Postmodernism Generator (wiki), which creates a random postmodernist essay every time the page is loaded. Another example is SCIgen (wiki), which can generate random papers about computer science. Your task in this popularity contest is to write a program that can generate random, convincing paragraphs of academic logorrhea. You can choose what topic your program will generate text about. Postmodernism, CS, math, physics, and philosophy seem to be likely choices, but you can choose something else. • Your program must be able to take in a 32 bit integer (a value from 0 to 232-1) as a seed value and output a random paragraph of text on your topic. None of the 232 outputs should be identical. (If desired, you can include an option for no input, where the seed number is just chosen randomly.) • The paragraphs should be from 2 to 8 sentences long and between 300 and 1000 characters. The sentences should start with capitals and end with periods. Including other punctuation is optional. • The actual content of the sentences does not need to make grammatical sense, though it should consist of real English words. Presumably, the more it does make sense the more it will be upvoted. • You do not need to include author names or citations like the Postmodernism Generator does. You could though, and you are welcome to take some liberties and generate a full essay or a mini-paper or something if it's clear that what you're doing is more difficult that just generating a paragraph. • You may use any NLP libraries or resources, provided they don't already automatically generate random academic text. e.g. taking a paragraph from a random SCIgen paper would not be allowed at all. The highest voted answer wins. • Perhaps it needs to be narrowed down to a specific topic/area. How about homeopathy? – trichoplax Feb 25 '15 at 12:53 • @trichoplax: Randomly generated articles on homeopathy might end up getting published. ;) – Alex A. Apr 2 '15 at 2:57 • @AlexA. that would be priceless :) The winning condition could be the number of homeopathy journals it gets published in. – trichoplax Apr 7 '15 at 21:28 # Which Children Don't Play Well Together? [code-golfchallenge] You are a kindergarten teacher who is having problems with fights breaking out among the students. You have noticed that altercations happen only when certain groups of children are together. A group of children who can't play well together, but will coexist peacefully if any one student is removed from the group, is known as a MIKG (minimal incompatible kindergartener group). Every MIKG contains at least two children. To help prevent problems, you decide to identify all such groups of kindergarteners. Each day, your class has Group Reading Time. This involves dividing the children into groups of 1 or more students, who take turns reading pages from a picture book. If all the children from an MIKG are placed in the same reading group, a commotion will erupt. The distraction rapidly involves all the students in the class, so you can't tell which reading group it originated from. You want to find all the MIKGs as soon as possible, so you write a computer program to help you do the math. Let f(N) be the maximum number of days it will take to identify all the MIKGs in a class of size N, assuming an optimal strategy is used. The program should not take more than f(N) days to find the answer. ## Input/Output At the beginning of the program, it takes a positive integer input of N which tells the number of students in the class. Then, the program creates a plan for the day's reading groups. The user (kindergarten teacher) will input 1 if a disruption occurred during reading time, or a 0 if it remained calm. When the program determines all the MIKGs, it shall print them out and exit. ## Challenge You will be given random test cases for class sizes between (a) and (b). The goal is to determine the MIKGs in as few days as possible. The program that makes the smallest amount of queries is the winner, with tiebreak by earliest post. ## Restrictions • The program must respond in under (x) seconds • Due to the interactivity requirement, you must submit a full program, not a function. • You may specify any format for the I/O as long as it is clear, unambiguous, consistent, and doesn't use characters other than printable ASCII and newlines. ## Sandbox notes • I presume that an MIKG must contain at least two children, but it would be good to make that explicit. – Peter Taylor Mar 12 '15 at 9:01 # Musical Blinkenlights # Introduction If you take a look at the front panel of your desktop or laptop computer, chances are that you'll find a handful of blinkenlights, including a hard disk activity indicator. Image taken from here The idea of this challenge is to "play" the Shave and a Haircut melody with that light. # The Task Your task is to write a full program with the following behavior. If the program is placed in an empty directory, compiled (if applicable) and run, it causes the hard drive activity light to blink the notes of the Shave and a Haircut melody (unless, of course, the hard drive is active for some other reason). After that, it shall exit gracefully. # Precise Rules The specification of the melody is as follows. Let t be a unit of time between 0.2 seconds and 0.7 seconds. Starting from some time tinit, the activity light shall blink at tinit, tinit + t, tinit + 1.5*t, tinit + 2*t, tinit + 3*t, tinit + 5*t, and tinit + 6*t. The blink must be long enough to be noticed by the human eye, but no more than 0.25*t. Your program may create and modify any files and subdirectories in the directory it is placed in, including its own source code. The program does not have to be cross-platform, but you must state your operating system in your answer, and any necessary hardware requirements. In particular, some environments allow the blinkenlights to be controlled manually; this is perfectly acceptable, but must be explicitly stated. Your program may not damage or significantly alter the host computer. # Scoring This is code-golf, so the lowest byte count wins. Standard loopholes are disallowed. ## Sandbox Notes My main concern is whether my challenge would be too similar to this. • This seems somewhat hard to test. The hard drive activity in response to a given file access sequence could depend on the model of drive, the filesystem, and any number of filesystem or OS config options. I don't think it's reasonable to expect anyone to be able to state the hardware and config requirements. – Peter Taylor Mar 16 '15 at 14:48 • Musical nitpick: what you want is the Shave and a Haircut rhythm not melody. I thought you were asking something more difficult (especially as I didn't know that jingle was called that.) I like the challenge though. – Level River St Mar 24 '15 at 2:02 • I think this might have a problem - lots of processes go on at all times in a computer. It would be hard to predict when the light just blinks randomly, and you couldn't shut those processes down (i.e, compiz on Linux). Plus, how would the challenge be verified, and what if it was only qualified/disqualified because of a random blink? – ASCIIThenANSI Apr 7 '15 at 13:07 I've been reading this forum for a bit and I thought it might be a good idea to do a short sequence of challenges themed on famous mathematicians. It's my first post here so please point out any shortcomings. It is Irving Kaplansky's birthday today. Among other things he is famous for his conjectures on group rings. It is one of these conjectures in mathematics that requires virtually no special knowledge to understand. There a couple of words that need explaining in them but their definitions are very simple. These words are "group", "torsion-free group", "ring", "domain", "group ring", "idempotent", "unit". Please read up if you want to. This challenge doesn't require understanding these words or the conjecture. All that's needed is the concept of a finite cyclic group. I'm sure most of you know what it is, but I'll give a short introduction. A cyclic group of order n can be understood as what you get when you take something (whatever) called a generator, say p, and decide that it can be raised to integer powers. These powers can be multiplied like so: pk * pl = pk+l. But there's one catch: whenever the exponents of the powers give the same remainder from the division by n, these powers are considered equal. This means, in particular, that there are exactly n powers really: p0, p1,...,pn-1. Any other power is equal to one of these. The challenge is to implement a certain operation on certain formal expressions involving these powers. The expressions are of this form: r0 * p0 + r1 * p1 + ... + rn-1 * pn-1, where all ri are real numbers. The operation, called multiplication, consists in, first, multplying two such expressions as if they were real sums, that is for example, for n=3: (2 * p0 + 3 * p1 + 2 * p2) * (0 * p0 + 1 * p1 + 2 * p2)= (2 * p0) * (0 * p0) + (2 * p0) * (1 * p1) + (2 * p0) * (2 * p2) + (3 * p1) * (0 * p0) + (3 * p1) * (1 * p1) + (3 * p1) + (2 * p2) + (2 * p2) * (0 * p0) + (2 * p2) * (1 * p1) + (2 * p2) + (2 * p2). Then, we simplify each of the summands according to the rule (r * pk) * (s * pl) = (r * s) * (pk * pl) = (r * s) * pk+l. And finally, we simplify the resulting sum according to the rule (r * pk) + (s * pk) = (r + s) * pk. This means that for n=3, we have 2 * p2 + 5 * p5 = 7 * p2 because p2=p5! The resulting sum is again of the form r0 * p0+ r1 * p1 + ... + rn-1 * pn-1 after we order the summands by the exponents. This operation is exactly the product in the group ring R[C], where R is the field of real numbers and C is a finite cyclic group. This group ring doesn't satisfy the hypothesis of Kaplansky's conjecture because finite cyclic groups aren't torsion-free. Your task is to implement this in any language. Your program/procedure/whatever has to take a natural number n>0 as user input. This will be the order of your cyclic group. Then it has to take 2n "real numbers" as user input. I don't really care what the "real numbers" are in your implementation. They could be ints for all I care. Just make them something that can reasonably be interpreted as real numbers and has a reasonable arithmetic. The first n numbers will be the coefficients of the first formal sum and the other n numbers will be the coefficients of the second formal sum. You need to output the n coefficients of their product. You don't need to compute the product in the way describe above. It just has to be correct (modulo rounding errors and other things computers do wrong with numbers). Shortest code wins. You can assume the input is valid. Both input and output can be in any reasonable form. I'm not sure if this is a good restriction on this site, but I'd like you to think "actually usable". Though I don't really care about how long it takes to compute. I guess all standard loopholes apply, as I've noticed it seems to be a mantra here. :-) As I said, please help me improve this challenge and oh, feel free to edit. • Did you mean to shift the indices in "r_1 * p^0 + r_2 * p^1 + ... + r_(n-1) * p^(n-1)"? Also, do I understand right that you're asking for us to multiply formal polynomials under the relationx^n = 1? – xnor Mar 22 '15 at 22:53 • @xnor I didn't mean to do that! And yes, that's one way of saying this. Another way of saying it is to multiply elements of the group ring R[C] where C is a finite cyclic group and R is the field of real numbers. My goal is to introduce the concept of a group ring and this is one of the simplest cases. For the infinite cyclic group it would amount to the Laurent polynomials, and that's too familiar I think. This is the next simplest case. – ymar Mar 22 '15 at 22:59 • @Martin Done, thanks! – ymar Mar 22 '15 at 23:18 • @xnor I've corrected the indices (there were some more errors). Do you think this is too simple? I was thinking of doing it with the quaternion group... – ymar Mar 22 '15 at 23:19 • Added the statement that this is a group ring product. – ymar Mar 22 '15 at 23:23 • I think the problem is OK, but people might just do this by multiplying regular polynomials and then combining x^(n+i) with x^i. I like the group idea, but I've already done the quaternions. – xnor Mar 23 '15 at 4:03 • @xnor Well, for the quaternions it wouldn't be as simple. Perhaps I could stipulate that one of the answers to your problem should be used in some way? – ymar Mar 23 '15 at 4:16 • What do you mean that it wouldn't be as simple? – xnor Mar 23 '15 at 4:20 • @xnor I mean that it wouldn't be just a simple variation on polynomial multiplication. It's still similar because that's what the (semi)group ring multiplication is: a generalization of polynomial multiplication. But the case of the quaternion group is further away from polynomials than cyclic groups. – ymar Mar 23 '15 at 4:24 # Functioning HTML-Encoded Program Introduction When showing code to others on the web, some characters are generally replaced by their HTML-encoded entities. Browsers display this properly, but if a user copies the code directly from HTML or a script tries running the code without decoding its entities, the code will likely contain errors. Challenge You are to come up with a program that uses all of the following five characters: ", &, ', <, and >. When encoded to their named XHTML entities, the code must still run using the following respective entities: &quot;, &amp;, &apos;, &lt; and &gt;. The code must be able to run both ways without throwing errors. Each of the five characters must be used outside of comments and string-like objects at least once (ie. for JS, outside of literal regex). You may use an expression in place of a statement up to one time (if your language supports it). Example JS Script (1/5 required characters) Unencoded: (Sets lt to true) var lt = 6; lt = 3 < lt; Encoded: (Sets lt to 2) var lt = 6; lt = 3 &lt; lt; Encoder/Decoder Here's a converter to make testing your code easy (click run code to use): function encode() { document.getElementById('post').value = document.getElementById('pre').value.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/'/g, '&apos;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); if (entity=document.getElementById('pre').value.match(/&\S+?;/)) alert('Warning: Unencoded text may already have entities. (ie: ' + entity[0] + ')'); } function decode() { document.getElementById('pre').value = document.getElementById('post').value.replace(/&quot;/g, '"').replace(/&apos;/g, '\'').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&') if (entity=document.getElementById('post').value.match(/&(?:[\s;]|[^\s;]*(?:\s|$))|<|>|'|"/)) alert('Warning: Encoded text may contain unencoded characters. (ie: ' + entity[0][0] + ')');
}
<label for="pre"><b>Unencoded:</b></label> <button onclick="encode()">Encode</button><br /><textarea id="pre" style="width:100%;min-height:49px;resize:vertical"></textarea><br /><br />
<label for="post"><b>Encoded:</b></label> <button onclick="decode()">Decode</button><br /><textarea id="post" style="width:100%;min-height:49px;resize:vertical"></textarea>

The shortest functioning unencoded code block wins. Have fun!

• I would vote to close this as too broad, because as far as I can tell from the question, all the program has to do is not crash. It probably wouldn't be a good question even with a spec which required it to perform a stated task, though, because it's so easy to bypass the intent by using no-ops. – Peter Taylor Mar 27 '15 at 23:37
• @PeterTaylor That was the point of me including "You may use an expression in place of a statement up to one time (if your language supports it)," but I suppose that I can't assume that'll cover every case of no-ops in programming languages out there. – Pluto Mar 30 '15 at 19:40

# Print All Provable Statements

This might be a stretch to make into a challenge, but I think it can be done. The challenge will most likely be code-golf. I'm thinking about using 2D geometry as the basis. I will have to create a notation system for geometrical and logical statements that is golf-friendly.

The general idea is that you start off with a list of known facts. Then, the program uses the laws of logical deduction to work through every possible deduction that can be made, and then add these new facts back into the pool of knowledge. Given enough time, every possible provable statement will show up in your list. Of course, you will run out of memory first, and that's okay.

Probably the best axioms to use are Tarski's Axioms. From the wiki article:

Tarski's system has the unusual property that all sentences can be written in universal-existential form, a special case of the prenex normal form. This form has all universal quantifiers preceding any existential quantifiers, so that all sentences can be recast in the form

∀u∀v...∃a∃b...

This fact allowed Tarski to prove that Euclidean geometry is decidable: there exists an algorithm which can determine the truth or falsity of any sentence. Tarski's axiomatization is also complete. This does not contradict Gödel's first incompleteness theorem, because Tarski's theory lacks the expressive power needed to interpret Robinson arithmetic (Franzén 2005, pp. 25–26).

There are three (?) fundamental relations:

• x=y Equality - x and y refer to the same objects
• Bxyz Betweenness - The point z is between x and z, lying on line segment xz. It is possible for x=y or y=z.
• wx~yz Congruence - The length of line segment wx is equal to the length of line segment yz.

There are three congruence axioms:

• xy~yx Reflexivity of Congruence
• xy~zz → x=y Identity of Congruence
• xy~zu & xy~vw → zu~wz Transitivity of Congruence

There are also betweenness axioms:

• Bxyx → x=y Identity of betweenness
• Bxuz & Byvz → ∃a(Buay & Bvax) Axiom of Pasch
• Axiom Schema of Continuity: I'll need some help translating this.
• ∃a∃b∃c(!Babc & !Bbca & !Bcab) Lower Dimension

And some more:

• (xu~xv & yu~yv & zu~zv & u!=v) → (Bxyz | Byzx | Bzxy) Upper Dimension
• (Bxuv & Byux & x!=u) → ∃a∃b(Bxya & Bxzb & Bavb) Equivalent to Euclid's Axiom
• (x!=y & Bxyz & Bfgh & xy~fg & yz~gh & xu~fi & yu~gi) → zu~hi Five Point
• ∃z(Bxyz & yz~ab) Segment Construction

## Some notes on mathematical notation.

I think it would be a good idea to convert all math notation to ASCII. I've done with with congruence already, but I need replacements for → ∃ ∀. I might replace a!=b with !a=b for consistency, or I could go all-out and put everything in Polish notation.

## If I wanted fancier axioms

Here is an alternative set of axioms, which are based on Hilbert's geometry axioms but excluding the ones that talk about planes. Some of them are copied verbatim from that website and may be unnecessarily fluffy. I would have to re-write all of them to be in formal notation.

1. Given two distinct points A and B, then there exists exactly one line a that contains both points.
2. Given a line a, there exist at least two distinct points A,B which lie on the line and three distinct points X,Y,Z which are not on the line.
3. If a point B lies between points A and C, then points A,B,C are three distinct points on a line, and B also lies between C and C.
4. For two distinct points A and C, there exists at least one distinct point B such that C lies between A and B.
5. Of any three points on a line, there exists no more than one that lies between the other two.
6. Let A, B, C be three points that do not lie on a line and let a be a line which does not meet any of the points A, B, C. If the line a passes through a point of the segment AB, it also passes through a point of the segment AC, or through a point of the segment BC.
7. If A, B are two points on a line a, and A' is a point on the same or on another line a' then it is always possible to find a point B' on a given side of the line a' through A' such that the segment AB is congruent or equal to the segment A'B'. In symbols AB = A'B'.
8. If a segment A'B' and a segment A"B", are congruent to the same segment AB, then the segment A'B' is also congruent to the segment A"B", or briefly, if two segments are congruent to a third one they are congruent to each other.
9. On the line a let AB and BC be two segments which except for B have no point in common. Furthermore, on the same or on another line a' let A'B' and B'C' be two segments which except for B' also have no point in common. In the case, if AB = A'B' and BC = B'C' then AC = A'C'.
10. Let angle(h,k) be an angle and a' a line and let a definite side of a' be given. Let h' be a ray on the line a' that emanates from the point O'. Then there exists one and only one ray k' such that the angle(h,k) is congruent or equal to the angle(h',k') and at the same time all interior point of the angle(h',k') lie on the given side of a'. Symbolically angle(h,k) = angle(h',k'). Every angle is congruent to itself, i.e., angle(h,k) = angle(h,k) is always true.
11. If for two triangles ABC and A'B'C' the congruences AB = A'B', AC = A'C', angleBAC = angleB'A'C' hold, then the congruence angleABC = angleA'B'C' is also satisfied.
12. Let a be any line and A a point not on it. Then there is at most one line in the plane, determined by a and A, that passes through A and does not intersect a.
13. If AB and CD are any segments, then there exists a number n such that n segments CD constructed contiguously from A, along the ray from A through B, will pass beyond the point B.
14. An extension of a set of points on a line with its order and congruence relations that would preserve the relations existing among the original elements as well as the fundamental properties of line order and congruence that follow from Axioms I-III, and from V,1 is impossible.

Here's a puzzle to be split into two questions:

# Build an evil-defying Tetris AI

Build a program that takes the state of a current board and a piece and attempts to find the optimal space for it.

Your program will be scored by the number of points it can score against the evil Tetris block generators in the question below. Highest score wins. (scoring algorithm to come later)

# Build an evil Tetris block generator

Build a program that attempts to take the state of a current board and generate the worst possible piece for it.

Your program will be scored by the total number of points the AIs built in the question above can score against it. Lowest score wins.

• In general, if you mainly flood with S and Z then it's basically unsolveable. Also related :) – Sp3000 Apr 6 '15 at 13:44

# It's just a flesh wound!

The idea is to create a program that:

• If any one of the four quarters (counted in bytes) is removed, the program outputs "Tis' but a scratch" (exactly, with optional newline).
• If any two of the four quarters are removed, the program outputs "Just a flesh wound.".
• If any three of the four quarters are removed, the program outputs "Let's call it a draw, then.".
• The full program should output "None shall pass.".

Rules:

• The program has to have length divisible by four (4).
• The program must not read it's own source or it's length in any way.
• The output is to stdout if it is possible in your language (REPL output is considered valid in this case).
• The answer with the fewest bytes wins.
• I don't think this would actually be a duplicate of anything in the source-layout tag, but it doesn't feel like it would add anything to the sum of what's already in that tag. – Peter Taylor Mar 19 '15 at 19:17
• Would these 'quarters' be defined by the user, or is it any random 1/4th of the program? – ASCIIThenANSI Apr 5 '15 at 16:49
• @ASCIIThenANSI The quarters are successive quarters of the code. ie. the first one is 0 - 1/4, second is 1/4 - 2/4, third is 2/4 - 3/4 and fourth is 3/4 - 4/4 – seequ Apr 5 '15 at 17:48
• Would it be allowed to read the program's own length? – ASCIIThenANSI Apr 7 '15 at 13:03
• @ASCIIThenANSI No. Updated. – seequ Apr 7 '15 at 14:50
• Here's an idea: If it is full, it prints None shall pass., one-quarter, Tis' but a scratch., and three-quarters, Let's call it a draw, then.. – ASCIIThenANSI Apr 7 '15 at 14:55
• @ASCIIThenANSI Awesome. – seequ Apr 7 '15 at 15:41

# Programming Tetris Blocks (Even More Literally?)

In this challenge, you will write a Tetris AI. There's one twist though: the AI will operate from the perspective of the Tetris blocks themselves.

Note: I am worried about the novelty of this question. The key is "the perspective of the Tetris blocks themselves." In order to make this interesting, I have to give the AI a bare minimum of information needed to make a move. Otherwise, it will just be a regular Tetris AI challenge.

When a Tetris block is spawned at the top of the map, a new AI object is created. Each time step, and the block receives data about its immediate surroundings and returns a move (move left/right, rotate clockwise/counterclockwise, or nothing).

An idea as to "block vision": each of the four squares in a block each have four "eyes," one on each side. Each eye returns the distance to the nearest wall/block (including/excluding other squares in the same block?). This means that the AI will receive exactly sixteen numbers each update.

#######
# 1234#
#  #  #
#### ##
#######

If a 2D array where each row (1st level) is a square and each column (second level) is an eye in the directions [U,D,L,R], then here is what could be seen as input, with 0s representing an adjoining block.

[[1,2,2,0],[1,1,0,0],[1,3,0,0],[1,2,0,1]]

More details coming sometime not now.

• For 'block vision', what if returns -1 if it hits the same block? Also, shouldn't the squares be numbered left to right and up to down, so the I piece is [1][2][3][4], and an example 'block vision' would be [1, 2, 3, 1, 2, 3, 1, 2, 3, 4, 4, 4, 4, 4, 2, 2]? – ASCIIThenANSI Apr 14 '15 at 16:24
• @ASCIIThenANSI In your example, which numbers refer to which squares/eyes? – PhiNotPi Apr 14 '15 at 16:49
• Square 1 is the first 4 numbers ([1, 2, 3, 1]), square 2 the next 4 ([2, 3, 1, 2]), etc. The directions are in the format [U, D, L, R], and it works like [U, D, L, R, U, D, L, R, U, D, L, R, U, D, L, R]. – ASCIIThenANSI Apr 14 '15 at 17:10
• I couldn't really visualize where you were getting the numbers from, so I added my own example. – PhiNotPi Apr 14 '15 at 17:27

# Background

Consider the following grid:

a   b   c
|   |   |
|   |   |
|   |   |
d---+---+---+---e
|1  |2  |3
|   |   |
|   |   |
f---+---+---+---g
|4  |5  |6
|   |   |
|   |   |
h---+---+---+---i
|7  |8  |9
|   |   |
|   |   |
j   k   l

I've marked every endpoint with a letter a-l, and every + with a number 1-9. Imagine, for a moment, that this grid represents a small section of a town. Each | or - represents one segment of a two-way road, and each + represents an intersection, which will have a corresponding stoplight.

During the game, cars will be added and removed from the grid at the endpoints a-l. Cars move exactly one space (through one segment of road or through one intersection) per turn, and never change direction. Thus, if a car enters the grid at endpoint d, it will exit after reaching endpoint e. We may assume that the cars are smart enough to avoid all collisions. They will never move to a space occupied by another vehicle, and they will never enter an intersection when the stoplight they see is red. When a car reaches the opposite endpoint, it disappears and can be safely forgotten.

Assume that we have a variable entitled public_unhappiness that is initialized to 0.

If a car following the above rules may not move due to another vehicle or a stoplight, the value of public_unhappiness is increased by 1.

//SANDBOX NOTE: This formula is linear, but one could say that unhappiness goes up exponentially the longer you sit at a stoplight. This formula is subject to change.

We pit two bots against each other, both controlling traffic flow in different ways. One bot aims to maximize public_unhappiness and the other aims to minimize it. We will refer to the former as The Driver and the latter as The Traffic Engineer. Because this KotH is inherently unbalanced, Drivers and Traffic Engineers will face off in a round-robin tournament (playing only against the opposing faction) and will be placed in separate leaderboards.

# Input

Though the bots are different and rely on entirely different strategies, every bot has access to the same information. Every turn, the bots will be prompted with a list of command-line arguments. Below is a general format:

./Traffic_Troubles Your_bot.extension S1 S2 S3 S4 S5 S6 S7 S8 S9 N a,b,c a,b,c ...

S1 through S9 are binary digits that represent what direction traffic may flow through the corresponding stoplight. If the value is 1, traffic flows horizontally through this stoplight. If the value is 0, traffic flows vertically. Hence, a car approaching intersection 1 from the east will stop moving if the value of S1 is a 0, and continue moving along if that value is a 1.

The following argument is N. This represents the number of cars currently active on the board.

There then follows N descriptions of cars in the form a,b,c. Here, a is the character of the endpoint that a car originated, b is its destination, and c is the number of spaces it has moved. A car that has just been put on endpoint a has moved 0 spaces, and would thusly be described as a,j,0. On the other hand, a car approaching intersection 6 from the west would be described as f,g,11.

On the first turn, every stoplight has value 0, and no cars exist on the board (N == 0).

//SANDBOX NOTE: This input seems pretty messy... Any ideas?

# The Traffic Engineer

Traffic Engineers aim to minimize public_unhappiness by changing the values of the stoplights to allow for traffic to continue through.

You may specify the values of up to three stoplights per turn. Every turn your bot is called, you must provide up to 3 space-separated output pairs of the form a,b where a is the number of the spotlight you want to change, and b will be a binary digit representing the desired value of the stoplight. Invalid output will count as a change to the stoplights, but be ignored. You may choose to output any number of changes less than or equal to 3.

//SANDBOX NOTE: The value of 3 is subject to change.

# The Driver

Drivers aim to maximize public_unhappiness by choosing entry points for cars.

Every turn, you may output up to six distinct entry points for cars in the form X Y Z .... If a car already exists on that entry point and is not moving in the opposite direction that output will be ignored. You may specify any number of entry points less than or equal to 6.

//SANDBOX NOTE: The number 6 is subject to change

# The Sequence of Events

1. Both bots are called at roughly the same time with access to the exact same information.

2. Cars are added to the entry points and the value of stoplights are changed.

3. Cars move, and public_unhappiness is incremented accordingly.

4. Any car that has surpassed its respective exit point is removed from play.

//SANDBOX NOTE: Perhaps the Traffic Engineer should be able to view where the Driver put cars and adjust accordingly. Thoughts?

# Rules

1. Your bot is given 1 second to respond.

2. You may not tailor your bot to act specifically against another bot.

3. Please provide a method for compiling your bot and a command-line method for running your bot.

[Language-name] - [Traffic Engineer/Driver] - [Bot-name]

5. Standard Loopholes are disallowed.

//SANDBOX NOTE: If this idea is received well (~4-6 upvotes on the sandbox) I will build the controller. For now, it's just an idea. If you wish to run/improve on this KotH, you are welcome to.

# 8-FTU - Retrofit UTF-8 to any pre-1988 language

The design of Unicode started in 1987 and was first published in 1988. UTF-8 itself was designed in 1992 and first presented in 1993. Your goal is to retrofit the UTF-8 encoding of Unicode to any language that was in existence on 31 December 1987. You can't use any features that were added to the language after this date.

Your program will take a text input (byte encoded characters, possibly with errors) and up to two integers. Your program must accept any value at any byte position (00-FF).

### Task 1 - Validate the input

Your program will print one of TRUE/FALSE, True/False or true/false depending on whether the text is valid UTF-8 or not, and exit if the format is not valid. See below for validation rules. There are also many online resources that cover the format that you can reference.

### Task 2 - Count the code points

If your program didn't exit at the end of Task 1, it will print the number of Unicode code points encoded within the text.

Using the two integer inputs your program will find and output the matching substring. The first integer will be the starting position, 0 will be the start of the string. If the starting position is after the end of the string, return an empty string. The second integer will be the length of the substring in Unicode code points. If the length is omitted or goes past the end of the string return all the text from the start position to the end of the string. You do not need to program for negative numbers, although you can if you want to.

Tasks 1 & 2 must be printed to standard output. If printing the output of Task 3 would have undesirable consequences (e.g. characters interpreted as control codes) you may return the text instead. You don't have to worry about how the text will display, your code will be taken by DeLorean or TARDIS (depending on country) to 1987 or earlier where a team of engineers will work on displaying it correctly!

### Valid encodings

Code points        Byte encoding
---------------    -----------------
U+0000 - U+007F    Standard 7-bit ASCII (00 - 7F)
U+0080 - U+07FF    Two bytes per code point (C2 80 - DF BF)
U+0800 - U+D7FF    Three bytes per code point (E0 A0 00 - ED 9F BF)
U+D800 - U+DFFF    High and low surrogate pairs, invalid in UTF-8 (ED A0 80 - ED BF BF)
U+E000 - U+FFFF    Three bytes per code point (EE 80 80 - EF BF BF)
U+010000 - U+10FFFF    Four bytes per code point (F0 80 80 80 - F4 8F BF BF)

### Byte table

• 00 - 7F: Standard 7-bit ASCII
• 80 - BF: Continuation bytes
• C0 - C1: Invalid - Task 1 must print one of the false messages if either of these bytes are present
• C2 - DF: Start of two-byte code
• E0 - EF: Start of three-byte code. ED codes where the next byte is one of A0-BF are invalid because they encode surrogate pairs
• F0 - F4: Start of four-byte code. Note: not all sequences starting with F4 are valid. You need to test for these too
• F5 - FF: Invalid - Task 1 must print one of the false messages if any of these bytes are present

The remainder of a multi-byte code must only be continuation bytes until the length is reached. E.g. E4 85 B9 is valid because E4 marks the start of a three byte code, there are exactly three bytes and 85 and B9 are both within the range 80-BF. A continuation byte must not appear except as part of a multi-byte sequence, which must start with C2-F4. Long encodings are not allowed. E.g. "A" is 41, which could also be encoded as C1 81 or E0 81 81. These longer sequences are invalid because there is a shorter, valid sequence.

You don't need to worry about the BOM code point U+FEFF (EF BB BF). Treat it as any other character even if it appears within the text.

### Example input (to be expanded)

C3 87 61 20 76 61 3F 0 2 (Ça va?, 7 bytes, 6 code points)

Outputs:

True
6
Ça

C3 87 61 20 76 61 3F 2 (Ça va?, 7 bytes, 6 code points)

Outputs:

True
6
va?

C1 87 61 20 76 61 3F 0 2 (Ga va?, 7 bytes (overlong error), 6 code points)

Outputs:

False

As mentioned above, the output for Task 3 may be returned as a string instead of printing it.

### Scoring

Either shortest code in bytes or a bonus awarded for retrofitting an older language. Maybe bytes minus the number of months before January 1988, assuming a release date of December if not otherwise specified?

# KotHgress

As everyone knows, the only way to make sure your voice is heard among a group of people is to shout louder than everyone else. This is especially true in KotHgress, a bureaucratic committee of PPCG bots.

The KotHgress Register is a 1D string, at least 100 characters long, containing the minutes of each committee meeting. The only problem is that all the committee members talk at the same time, often shouting over each other, so that (like a typical committee), nothing ever gets done. However, since this is a committee of bots, efficiency is prized almost as much as volume.

# Rules

The Register for each meeting is a string of length max(100, N_bot * 4). At the beginning of each meeting, a committee member bot is pseudorandomly assigned an ascii character to be its voice, and 3 starting positions for its voice in the Register (initial index of 1), with each bot's positions having the same sum - for example, [1,4,100] and [5, 25, 75] could be starting positions.

Each turn, a bot receives 20 points times the number of times its voice appears in the Register. The bot can spend any amount of its points to bid on positions in which to place its voice. A bot that does not spend all its points banks any remaining points towards its score for the round; points do not carry over to following rounds.

Once all bids have been collected, each position is overwritten with the voice of the highest bidder, with ties for high bid causing no change in that position's current character. Note: a bot that is outbid for a position it already occupies loses that position.

Then, each bot accumulates score equal to the combined rank of its voice characters in the Register (for example, "ABABB" would score 4 for "A" at rank 1 and 3, and 11 for "B" at rank 2, 4, and 5), and the Register is sent as input to each member for them to choose their next bids.

After 100 turns, the meeting is over, and the bot with the highest accumulated score wins the meeting.

# Input

Each turn, bot will receive four inputs, in this order:

1. a single character which is its voice
2. a positive integer indicating its current (banked) score
3. a positive integer indicating the number of points it collected this turn
4. a string of length max(100, N_bot * 4), the Register

# Output

The bot should output a string consisting of integer pairs, separated like so: "pos0 bid0|pos1 bid1|...|posM bidM". Banked points will be automatically calculated from the output: banked_points = turn_points - sum(bids).

Invalid output, including sum(bids) > turn_points, will cause your bot to lose its turn (not banking any points).

# Meta-notes

• Controller construction is in progress.
• I expect it to be language-agnostic (using a similar setup to aBOTcalypse). Bots will be allowed one storage file for memory purposes.
• I understand that a > z, A > a, and A > Z. But which would be greater: a or Z? And is the bot with voice a placed before or after the bot with voice b? – ASCIIThenANSI May 15 '15 at 13:10
• I was figuring on going in ascii order, so A->Z->a->z'. That allows for 52 committee members; I can do non-alphas if we get more interest than that, lol. – sirpercival May 15 '15 at 13:33
• OK. Just make sure that you add that to the rules. You could also use some of ASCII's 95 printable characters (minus space, and maybe take out some others that could mess up the input.) – ASCIIThenANSI May 15 '15 at 13:43
• I'll be a little more specific about this, sure. – sirpercival May 15 '15 at 15:02
• This has the classic KotH flaw: the best strategy is either to be purely random or to be the last person to submit your bot, and to metagame it against everyone else's bots. – Peter Taylor May 17 '15 at 16:01
• how would one metagame? the priority order is randomized at the beginning of each meeting – sirpercival May 17 '15 at 16:19

# Time Travel in KotH

This is not a question but a possible mechanic for KotH (type challenge).

In KotH we can ask each program (player) to store all its memory in a file between steps. This makes it possible to change a player's memory to an older one which is not possible with human players. This fact makes it possible to crate time-traveling based games.

I will outline to mechanics here, a simpler one (Time Reverters) and a more complex one (Time Travelers). Both will use a simple game to show how they would work.

# Time Reverters (mechanic I)

## A very simple example game

• Two players, N rounds.
• At every round a random player scores a point.
• The winner is the player with more points after round N.

## The time reverse twist

• At any time in the game a player can chose to time travel (TT) back to any previous round. This means the players will receive the memory they had at that round and forget everything else. Neither of them will know a TT happened.
• Each player can TT K times and this is counted by the controller. If a player tries to travel when it has no more travels left, the TT request is simply ignored.

# Time Travellers (mechanic II)

(will be written later...)

# Split multi-language no-space sentences

You will be given a string representing a sentence without word any boundaries. Additionally, you're given a dictionary of all possible words. Output all possible possible ways of splitting the sentence into words.

But there's a catch! The sentence was written by a drunken polyglot and contains words from multiple languages mixed together. Luckily, you've already got a dictionary of which words from different languages cirrespond to each other. So for each word, you should output its surface form (as it appears in the input sentence) and base form (eg. English). To prevent meaningless interpretations of a sentence as many one-letter words and abbreviations, sort the output by the number of words of each interpretation, lowest first.

Example:

teeistunnationalgetränkdeeikoku

tee/tea ist/is un/a national/national getränk/drink de/of eikoku/england

Given the dictionary below, the first word can only be tee, German for tea. Then comes is, which is already the English is. Then un, French for a. And so on.

tea => tea, tee, cha

is => is, ist, est, dess

a => a, ein, un, une, aru

national => national, kokkateki

drink => drink, getränk, nomimono

of => of, de, von, no

england => england, angleterre, igirisu, eikoku

Each entry of the dictionary is of the form:

<base_form> => <surface_form_1>, <surface_form_2>, ...

That is, the dictionary contains the base form (here English is used), and a list of possible variations in different languages for each.

See below for examples with multiple possibilities.

# Scoring

Code-golf.

(Golfed explanation. Ungolfed: The answer with the shortest code as measured by its bytesize in an encoding the interpreter or compiler accepts without additional flags wins. Multiple files add a penalty of 1 byte for each additional file. Flags add to the score.)

# Rules

• The defaults apply, function or program.
• You may assume there exists at least one solution.
• Your program must run in a reasonable amount of time, so don't just try every possible combination of words. Be prepared for a dictionary that contains hundred or thousands of words. Let's say about ~10 minutes on a modern PC.
• You must support unicode, at least the basic multi-lingual plane, codepoints 0x0000 - 0xFFFF. If your language of choice does not support unicode, you can emulate it using a fixed-length unicode encoding: consider each n bytes of the input sentence a letter.
• You do not need to worry about unicode modifiers, normalizing etc. -- each codepoint is considered a unique "letter".

# Input

• The defaults apply, stdin, command line argument, function argument, javascript prompt etc.
• The input sentence is given as a string (teaist) or list/array ([t,e,a,i,s,t])
• You may assume the input sentence is already in lower case.
• There is no additional punctuation in the input sentence to take care of.
• However, the input sentence and the dictionary may contain "words" with commas, periods, etc., ie. every unicode codepoint from the basic multilingual plane. It will not contain any of the codepoints 0x00-0x20, which means no null-bytes, spaces, tabs, newlines, so you can use them for separating the output.
• The dictionary may be in any format of your choice, but it must contain an association between a base form and all possible surface forms. It must not list all base forms for each surface form.
• You may also read the dictionary from a file, and take the file name or raw data as input.
• You may also assume the dictionary has already been stored in one variable of your choice. If you do, please provide some code for reference how I can put custom data in it, or read the dictionary from a file. However, it must not be pre-processed and as close to a hash (eg. {<base_form> => [ <surface_form_1>, <surface_form_2>, ... }) or array/list (eg. [ [<base_form>,<surface_form_1>,<surface_form_2>,...], [<base_form>,...], ...]) as possible in your language.
• You may choose whether the list of surface forms includes the base form or not, eg. big => big, gross or big => gross.

# Output

• The defaults apply, stdout, stderr, return value, javascript alert, etc.
• It should not need to be said, but if you output to stderr, nothing else but the solution must go to stderr, unless it's a compiler/interpreter warning that can be turned off by a flag.
• A list/array of all possible interpretations of splitting the sentence into words, sorted by the number of words.
• Each interpretation is a list/array of words. Each word is pair/list/array containing the surface form and the base, you may choose in which order. The words must be ordered as they appear in the input sentence.
• Alternatively, the array may be flattened.
• Alternatively, output two lists/arrays, one containing the base form for each word, and one the surface form.
• Alternatively, output a string representation of the array/hash/list.

For example, you could output an array

[["tee","tea"],["est","is"]]

or a flattened array

["tee","tea","est","is"]

or two arrays

["tee","est"]

["tea","is"]

or a string representation such as tee:tea:est:is or tee\ttea\nest\tis\n (\t tab, \n newline). But make sure you're escaping characters properly.

# Test cases:

First line is the input string. Each following line is a possible way of placing word boundaries, surface/base. Afterwards a sample dictionary is provided.

## 1

Note that some words contain a semi-colon.

abcd;efghi

ab/test cd;ef/awesome ghi/result

a/only bcd/test ;ef/awesome ghi/result

with the dictionary:

test: ab, bcd

awesome: cd;ef, ;ef

result: ghi

only: a

yahoo: abcd;efgh

## 2

sumomouserune

sumo/sumo mouse/mouse rune/rune

sumomo/plum useru/lose ne/right

with the dictionary:

sumo: sumo, mouse:mouse, rune: rune, plum: sumomo, lose: useru, right: ne

## 3

koukousensei

koukou/school sensei/teacher

koukou/shiptravel sensei/starfortunetelling

with the dictionary

school: koukou, teacher: sensei, shiptravel: koukou, starfortunetelling: sensei

## 4

unicode support:

with the dictionary:

sira:白, haku:白, kumo:雲, uñ:雲

## 5

Note the order of the results.

aaaa

aaaa/test

a/test aaa/test

aa/test aa/test

aaa/test a/test

a/test a/test aa/test

a/test aa/test a/test

aa/test a/test a/test

a/test a/test a/test a/test

with the dictionary:

test: a, aa, aaa, aaaa

I'll add a larger example should I post this.

• This is basically like a previous suggestion I made, but less complicated. My main motivation had been parsing Japanese kanji compounds, hence the unicode support, but I translated it into something more familar to non-Japanese speakers. – blutorange May 20 '15 at 19:21

## Snake vs labyrinth

Write a program that takes as input a text file representing a labyrinth and checks if this labyrinth can be entirely filled with a snake path. The program should output true or 1 if this is the case, false or 0 else.

The snake can enter the labyrinth at any point. He can move one cell up, left, right or down; once he has crossed a cell of the grid, he cannot go back to that cell. The snake cannot cross a wall or the borders of the labyrinth.

The labyrinth file is a grid of m x n characters, containing either # (wall) or . (empty space).

Example 1

should return true

.

Example 2

should return true

..
..

Possible solution (S = snake start, E = snake end, v = go down, < = go left)

Sv
E<

Example 3

should return true

...
.#.
...

Possible solution (S = snake start, E = snake end, v = go down, < = go left, > = go right, ^ = go up)

S>v
E#v
^<<

Example 4

should return false

.#
#.

Example 5

should return false

#.#
...

Example 6

should return false

.#.
...
...

This is code-golf, so the shortest code wins.

• I take it there aren't any limitations on efficiency? I seem to remember it's an open problem whether HAM-PATH is hard on subgraphs of the grid graph, and if so, you won't be getting an poly-time algorithms. – xnor May 22 '15 at 9:13
• @xnor Yes, no limitations on time/efficiency – Arnaud May 22 '15 at 11:59

Given an input, calculate the correct suffix and output the number in a readable format. The suffixes must go to at least 10^3000, in which the rules for calculating them can be found here, or a list can be found here.

For example:

10000 = 10.0 thousand
135933445 = 135.93 million
-2 = -2.0
-2.36734603 = -2.37
'1'+'9'*3000 = 2.0 nongennovemnonagintillion

Rules:

• No getting things from external resources - it must all be calculated within the code.
• External modules are fine as long as it doesn't breach the above rule.
• The input should work when input as a string, integer or float.
• The output must always contain a decimal place.
• The output must be rounded if above 2 decimal places.
• Leaving zeroes at the end is optional, as long as it doesn't go above 2 decimals (1.00 or 1.0 are both fine) and is consistent for all inputs (1 should output the same as 1.0).
• Must not throw an error no matter how high or low the input is.

Scoring:

• Score is the length of the code, including indents.
• Lowest score wins.
• It does not need to be a function, printing the output is fine.

As a starting point, here is an ungolfed version of some code to generate the list of suffixes. Feel free to build upon this or start from scratch.

a = ['', 'un','duo','tre','quattor','quin','sex','septen','octo','novem']
c = ['tillion', 'decillion', 'vigintillion', 'trigintillion', 'quadragintillion', 'quinquagintillion', 'sexagintillion', 'septuagintillion', 'octogintillion', 'nonagintillion']
d = ['', 'cen', 'duocen', 'trecen', 'quadringen', 'quingen', 'sescen', 'septingen', 'octingen', 'nongen']

num_dict = ['']
num_dict.append('thousand')
num_dict.append('million')
num_dict.append('billion')
num_dict.append('trillion')
num_dict.append('quintillion')
num_dict.append('sextillion')
num_dict.append('septillion')
num_dict.append('octillion')
num_dict.append('nonillion')

for prefix_hundreds in d:

#tillion can't be used first time round
if not prefix_hundreds:
b = c[1:]
else:
b = c

for prefix_tens in b:
for prefix in a:
num_dict.append(prefix_hundreds+prefix+prefix_tens)

For the record, my result is 578 characters. To be fair I'm surprised I couldn't find this being asked before :P

• The meat of this challenge is basically just the reverse of this one, which may explain why you haven't seen it this way. – Geobits May 27 '15 at 16:07
• "The input can be in any format, not just integers." is far too vague. "The output must be rounded if too long." needs to define "too long", and ideally give a rounding rule (e.g. floor, ceiling, nearest half-up, nearest half-down, nearest half-even, nearest half-odd). – Peter Taylor May 30 '15 at 13:46
• Thanks, sorry I'd missed the first answer, that is quite similar haha. This one should use 10x the values and may golf better with outputting the number instead of reading the input. And is the rounding rule actually needed? I generally meant what the default rounding functions do (that you learn in school), which is like half up, but then half down when you're below 0. – Peter May 31 '15 at 8:45
• Ended up busy with other stuff recently so only just remembered about this, would it be worth posting, or is it too similar to that other question? – Peter Jul 13 '15 at 21:46

# Code Bots ϕ

This is a challenge based on the popular Code Bots ("What's wrong with public variables?") challenge.

I made a few observations during the development of the original Code Bots:

1. I had a literal ton of ideas and wouldn't stop harassing Nathan Merrill about them.
2. Nathan Merrill already claimed Code Bots 2.

The solution is obvious: make my own challenge. So, that is exactly what I intend to do.

Note: I am working on various ways to distinguish the two challenges.

## Variables

Note: I have changed the names of some variables to make them more "intuitive."

The variables A and B each store an integer 0-23.

The variable C (for Control) stores an integer 0-23 and is incremented at the end of every turn. It indicates which line of the program is to be executed.

The variable D (for Direction) stores and integer 0-23, which determines the current direction of the bot. The direction is determined by {north east south west}[[D % 4]].

The variable E (for Entropy) is overwritten by a random integer at the end of each turn, but only if your bot uses it that turn.

The variable F (for Feeling) provides a sense of touch. This allows you to detect when a bot is next to you. The value equals the number of adjacent bots. For example, F equals 4 when you are completely surrounded on all four sides (and thus out of luck).

The variable G (for aGe) provides a timer. The value is incremented after the end of every turn, mod 24. This allows an easy way to do for-like loops.

## Instructions

Each line contains a single command, and each command takes a variety of arguments.

Flag : This represents your flag. Your goal is to smear your flag across the known universe. Each flag line has a hidden identifier denoting the owner. These lines do nothing upon execution.

Move : This moves the bot 1 unit forward in the direction that it is facing.

Copy [expr|line] [var|line] : This copies one expression to another. Both expressions must be of the same type. You can copy a line to another line or copy the value of one variable to another. Copying to yourself has a new advantage in that, instead of making an immediate change, the change is made just prior to the start of your next turn.

Copy2 [expr|line] [var|line] : This is a new version of copy, but instead of performing the action immediately after your turn, it performs the action immediately before your next turn. [todo: find a better name for it. Maybe "DelayCopy"]

If [cond] [line] [line] : This is an If statement, one of the most important statements. If the conditional evaluates to true, then the first of the two lines is executed immediately afterwards (on the same turn). If the conditional is false, then the second line is executed immediately afterwards. In order to prevent infinite loops of various kinds, a bot is not allowed to execute the same line twice in a single turn.

Jump [expr] [cond] : This is a new instruction designed to help speed up bots. Given a number N, it immediately sets the value of C to N and then executes #N on the same turn. The condition is optional, but if present it will determine whether or not the Jump command is executed or not.

Block [var|line] : This blocks a certain variable or line. Each variable or line can be blocked once, and this block prevents one modification attempt of that variable/line. If an opponent (or yourself) attempts to modify that variable, then the variable is merely unblocked rather than modified.

## Arguments

There are four types of arguments, var, line, expr, and cond. Here are their relationships:

var = *[var] | A | B | C | D | E
expr = [var] | [expr][op][expr] | [literal number]
op = + | - | %
line = *[line] | #[expr]
cond = [expr] | [line] | [expr]=[expr] | [expr]==[expr] | [line]=[line] | [line]==[line]

There are three types of operators which can be used in expressions: Addition +, Subtraction -, and Modulo %. The modulo operator has highest preference (left to right), with addition/subtraction being applied afterwards.

There are several different kinds of conditionals.

1. If [expr] usually returns true if the value of the expression is non-zero. There are several special cases. If D returns true if there is a bot directly in front of you. If E returns true if E is odd. (Note: add more special cases)

2. If [line] returns true if the line contains a flag.

3. If [expr]=[expr] returns true if the two expressions are equal mod 4.

4. If [line]=[line] returns true if the two lines are the same type (same command).

5. If [expr]==[expr] returns true if both expressions are equal mod 24.

6. If [line]==[line] returns true if the two lines are exactly equal (such as both flags having the same owner).

## The Turn Structure

(Initially, all variables are 0 except for E)
[command execution starts]
The command at line #C is executed.
If there is a chain of logic, it is followed until it stops or a line is visited twice.
The effect of a Copy statement is applied, if any.
C is incremented
If needed, E is randomized.
(other bot's turns here)
F is updated
The effect of a Copy2 statement is applied, if any.
[next command execution]

## Line Labels

To increase the ease of writing bots, there will be new things called line labels, which look like this word: and can be placed at the start of a line. Later in the code, you can reference the line label like this :word. (Note: The exact formatting is up for discussion).

During preprocessing, the controller will replace all instances of :word with the number of the line labeled word:. If the :word label is the only thing on the line (no command) then the entire line will be copied into that blank line. Here is an example:

main: If D #:move #:attack
:main
:main
Jump :main
move: Move
attack: Copy #:flag *#*C

## Other usability features

The language will be completely case-insensitive. Comments will take the form of //comment.

## The Arena

There will be 50 bots of each type entered into an arena. Initially, all of the bots will be evenly spaced on a grid and facing north.

....@.......@.......
.......@.......@....
..@.......@.......@.
.....@.......@......
@.......@.......@...
...@.......@.......@
......@.......@.....
.@.......@.......@..

Note: I believe this to be an improvement because the bots are not directly lined up with each other. In Code Bots 1, a bot could Move on its first turn and end up right behind another bot. In this grid, a bot has a much smaller chance of

## A complicated example bot

Each bot can contain up to 24 lines, and each line contains an instruction. If there are any blank lines (after substitution with line labels), then those lines are filled by Flags.

main: If D #:attackloop #:move        //attack if an opponent
:main                             //automatically filled in with the same line
loop: jump :main                  //executes line 0 again and sets C to 0
move: if T #:run #:turn           //always move (never rotate) when being attacked
run: Move
turn: If E #:run #:turn2          //randomly pick move or rotate
turn2: Copy2 D+1 D
attackloop: jump :attack
attack: Copy #:freeze *#*C         //freeze the opponent
plant: Copy #C+6 *#E              //plant your flag
:plant
:plant
:plant
freeze: Copy2 C-1 C             //this creates an endless loop when executed

After preprocessing, the above bot turns into the bot below. You can also simply submit the bot below without using any line labels if you'd like.

If D #8 #3
If D #8 #3
Jump 0
If T #4 #5
Move
If E #4 #6
Copy2 D+1 D
Jump 9
Copy #14 *#*C
Copy #C+6 *#E
Copy #C+6 *#E
Copy #C+6 *#E
Copy #C+6 *#E
Jump 2
Copy2 C-1 C
Flag
Flag
Flag
Flag
Flag
Flag
Flag
Flag
Flag

## Short, Useful Code Snippets

Block #G
Jump 0 G   //block all the lines in 24 moves

A covering array is an N by k array in which each element is one of {0, 1, ..., v-1} (so v symbols in total), and for any t columns chosen (so an N x t array) contains all possible v^t tuples.

Input: N, k, t, v (all 4 are positive integers), and then N x k integers, each of which comes from {0, ..., v-1}. Each of the integers are separated by spaces.

Output: Yes if the input is a valid covering array, and No if it is not.

Goal: in any language you want, write a program that validates if the input is a covering array in the fastest time. I will run programs on my machine, which is a Macbook Pro 2.2 Ghz Intel i7 with 16 GB RAM.

• Are you planning a follow-up which asks people to generate minimal covering arrays? That seems to be the more interesting direction. – Peter Taylor Jun 11 '15 at 5:31
• @PeterTaylor that's actually a cool idea, but other than v=t=2, the minimal case is not known, and no explicit construction is known (other than orthogonal arrays, which only work for one value of k). One question could be to ask for the best known minimal CA, which is actually something I'd really like (because it is part of my research). – Ryan Jun 11 '15 at 11:46
• I was thinking of a code-challenge which scores by the best CA for certain parameters, possibly required to be deterministic and inside a certain time limit. – Peter Taylor Jun 11 '15 at 12:33
• @PeterTaylor I like that idea, possibly allowing any technique such as simulated annealing. – Ryan Jun 11 '15 at 21:02