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

# Is this a narrow Thumb instruction?

ARM Thumb was originally a 16-bit only subset of the 32-bit ARM instruction set.

However, later versions added 32-bit "wide" instructions which were more flexible, and called the original, more restrictive 16-bit instructions "narrow" instructions.

The assembler now chooses between narrow and wide instructions automatically, depending on how the instruction was written. However, this meant that the syntax had to be changed to have specific rules.

Your job is to be this assembler.

However, the programs you parse are not that interesting; they will only ever consist of add and adds.

More specifically:

Your task is to write a function or program that will take an add/adds instruction, and return a truthy value if it is a valid narrow instruction, or a falsey value if it is not.

### Syntax rules

• ARM has 16 registers, r0-r12, r13 (aka sp), r14 (aka lr), and r15 (aka pc). For ease of parsing, we are going to refer to all registers by their number, instead of using the special register names.
• Do note the names when reading the official docs, as there are a lot of special cases for sp and pc.
• In Thumb mode, these are split into "Lo registers", which are r0-r7, and "Hi registers" which are r8-r15. Many instructions can only use Lo registers.
• Many instructions use the same source register as the destination register, even if they are written with three operands.
• add and adds are distinct instructions. adds affects the condition flags, while add does not. That is the difference, if you were wondering.

The following 6 forms are valid for narrow instructions (adapted from here):

1. adds x, y, #imm: x and y must both be Lo registers, and imm is a 3-bit constant from 0-7.
2. adds x, y, z: x, y, and z must all be Lo registers.
3. add x, x, y: x and/or y must be Hi registers. Note that x is repeated twice.
• We are ignoring the fact that ARMv6 relaxed this rule to keep it interesting.
1. adds x, x, #imm: x must be a Lo register. imm is an 8-bit constant from 0-255. Again, note that x is repeated twice.
2. add r13, r13, #imm: imm is a constant multiple of 4 in the range 0-508.
3. add x, y, #imm: x must be a Lo register, and y must either be r13 or r15. imm is a constant multiple of 4 in the range 0-1020.

Everything else is either a wide instruction or not valid.

### Other notes

Standard loopholes, everything must be self-contained, and you are only allowed to treat it as text. You can't feed it to an assembler (unless you include the assembler source code in the result, but.. ｗｈｙ).

The input can either be a string argument or text from stdin.

You can assume the format will match the following format (all lowercase, separators being a single space):

{add or adds} reg, reg, {#imm or reg}


Where imm is a non-negative number in base 10 (yes, including zero).

As a regex pattern:

^adds? r([0-9]|1[0-5]), r([0-9]|1[0-5]), (#[0-9]+|r([0-9]|1[0-5]))$ ### Reference implementation In case the rules are difficult to follow, here is a reference implementation I made in C. Yes, I deliberately overabstracted it to make you do all the work. I resisted the urge to post the reference implementation in ARM Thumb assembly, as that would be genuinely evil. 😏 You will not need to do the same error checking I did here. You can always assume the string itself is valid. The error checks in the main function are mostly to show what CAN'T happen. #include <stdlib.h> #include <stdint.h> #include <stdio.h> #include <stdbool.h> #include <errno.h> #include <inttypes.h> struct thumb_add_insn { char opcode[5]; uint32_t op1; uint32_t op2; char op3_prefix; uint32_t op3; }; // Returns whether the opcode ID is adds. static inline bool is_adds(const char *opcode) { return strcmp(opcode, "adds") == 0; } // Returns whether this register ID belongs to a Lo register, // specifically r0-r7. static inline bool is_lo_reg(uint32_t reg_id) { return reg_id <= 7; } // Returns whether this register ID belongs to a Hi register, // specifically r8-r15. static inline bool is_hi_reg(uint32_t reg_id) { return reg_id >= 8; } // Returns whether the operand prefix is for an immediate // value, specifically, '#'. static inline bool is_imm(char c) { return c == '#'; } // adds x, y, #imm3 static bool is_form_1(const struct thumb_add_insn *insn) { return is_adds(insn->opcode) && is_lo_reg(insn->op1) && is_lo_reg(insn->op2) && is_imm(insn->op3_prefix) && insn->op3 <= 7; } // adds x, y, z static bool is_form_2(const struct thumb_add_insn *insn) { return is_adds(insn->opcode) && is_lo_reg(insn->op1) && is_lo_reg(insn->op2) && !is_imm(insn->op3_prefix) && is_lo_reg(insn->op3); } // adds x, x, #imm8 static bool is_form_3(const struct thumb_add_insn *insn) { return is_adds(insn->opcode) && is_lo_reg(insn->op1) && insn->op1 == insn->op2 && is_imm(insn->op3_prefix) && insn->op3 < 256; } // add x, x, y static bool is_form_4(const struct thumb_add_insn *insn) { return !is_adds(insn->opcode) && !is_imm(insn->op3_prefix) && (is_hi_reg(insn->op1) || is_hi_reg(insn->op3)) && insn->op1 == insn->op2; } // add r13, r13, #imm static bool is_form_5(const struct thumb_add_insn *insn) { return !is_adds(insn->opcode) && insn->op1 == 13 && insn->op1 == insn->op2 && is_imm(insn->op3_prefix) && insn->op3 <= 508 && insn->op3 % 4 == 0; } // add x, y, #imm, y == r13 or r15 static bool is_form_6(const struct thumb_add_insn *insn) { return !is_adds(insn->opcode) && is_lo_reg(insn->op1) && (insn->op2 == 13 || insn->op2 == 15) && is_imm(insn->op3_prefix) && insn->op3 <= 1020 && insn->op3 % 4 == 0; } // Parses a Thumb add/adds instruction. // Returns 1 if it is a narrow instruction, 0 if it is not, // and -1 on an error. int is_narrow_add(const char *str) { // Note that you do not have to do error checking for the // competition. if (str == NULL) { errno = EINVAL; return -1; } // Allocate a 24 byte struct on the heap for good measure struct thumb_add_insn *insn = calloc(1, sizeof(*insn)); if (insn == NULL) { return -1; } // Parse the instruction with sscanf. // {adds} r{0}, r{3}, {#}{3} if (sscanf(str, "%4s r%"SCNu32", r%"SCNu32", %c%"SCNu32, insn->opcode, &insn->op1, &insn->op2, &insn->op3_prefix, &insn->op3) != 5 || (strcmp(insn->opcode, "add") != 0 && strcmp(insn->opcode, "adds") != 0) || insn->op1 > 15 || insn->op2 > 15 || (insn->op3_prefix != 'r' && insn->op3_prefix != '#') || (insn->op3_prefix == 'r' && insn->op3 > 15) ) { errno = EINVAL; free(insn); return -1; } int ret; // Test against each of the forms if (is_form_1(insn)) { ret = 1; } else if (is_form_2(insn)) { ret = 1; } else if (is_form_3(insn)) { ret = 1; } else if (is_form_4(insn)) { ret = 1; } else if (is_form_5(insn)) { ret = 1; } else if (is_form_6(insn)) { ret = 1; } else { // not a match ret = 0; } free(insn); return ret; }  ### Test cases adds r6, r3, #0 // true, form 1 adds r0, r1, #7 // true, form 1 add r0, r1, #3 // false, must be "adds" adds r0, r9, #1 // false, r9 is a Hi register adds r0, r1, #9 // false, must be 0-7 adds r0, r0, r0 // true, form 2 adds r7, r1, r2 // true, form 2 adds r4, r4, r1 // true, form 2 add r7, r1, r2 // false, must be "adds" adds r13, r14, r6 // false, r13 and r14 are Hi registers (this isn't even valid as a wide instruction) adds r0, r0, #0 // true, form 3 adds r5, r5, #249 // true, form 3 add r6, r6, #31 // false, must be "adds" adds r3, r3, #256 // false, must be 0-255 adds r8, r8, #72 // false, r8 is a Hi register add r4, r4, r11 // true, form 4 add r8, r8, r5 // true, form 4 add r9, r9, r9 // true, form 4 add r14, r14, r12 // true, form 4 add r8, r9, r10 // false, Rd must be the same add r1, r1, r0 // false, one must be a Hi register (we are ignoring the ARMv6 change) add r13, r13, #0 // true, form 5 add r13, r13, #48 // true, form 5 adds r13, r13, #64 // false, must be "add" add r13, r13, #17 // false, not a multiple of 4 add r13, r13, #512 // false, must be 0-508 add r0, r15, #0 // true, form 6 add r4, r13, #1000 // true, form 6 add r11, r13, #32 // false, r11 is a Hi register add r2, r13, #4000 // false, must be 0-1020 adds r7, r15, #384 // false, must be "add" add r3, r15, #127 // false, not a multiple of 4  Things you can safely ignore: // String will never be empty adds r1, r2 // don't worry about implicit middle operand adds R4, #12 // same adds r3, r3, #-3 // adding a negative is not even a thing add r0, r0, r99 // the only registers are r0 - r15 add r13, r13, #0x32 // it is base 10 subs r1, r1, r2 // only add and adds need to be handled add r2, r2, lr // you don't need to handle the special names add r0, sp, #0 // same add #3, r1, r1 // only the last one will be an immediate adds r3, r3, 32 // all immediates are prefixed with # ADDS R0, R0, R1 // everything is lowercase adds r2, r3 , r4 // only one space adds r2,r3,r4 // there will always be spaces addeq r0, r0, r1 // no IT blocks adds.n r0, r0, r1 // no manual width specifiers add r1, r2, r3, lsl #8 // no barrel shifting  This is , so the shortest answer in bytes per language wins. Proposed tags: and maybe but I think that is for things you must write in assembly, not parsing assembly itself. # Match me if you can cops-and-robbersregular-expressionrestricted-source Related ### Cops' Challenge Write a full program that outputs a regular expression that matches the entire source code of your program. Rules: • Your program may be written in any freely available language listed on Try It Online, Esolang, or Rosetta Code at the time this challenge was posted. • Similarly, you may choose any regex flavour natively supported by any freely available language (as defined above). The chosen flavour need not be natively supported by the language in which your program is written. You may exploit version-dependent behaviour of the regex engine provided that you specify which version you use. • Any feature of the chosen regex flavour (including modifiers and non-regular extensions such as backreferences and lookarounds) may be used. • The regex may match other strings apart from your program. • Regex delimiters should not be included in the output. Cops initially reveal their chosen language, the regex, and its flavour, but not their program. ### Robbers' Challenge Choose an uncracked cop submission written by another user. Write a full program in the same language that outputs the cop's regex identically. The entire source code of your program must also match the regex (in the flavour chosen by the cop). Any program that meets these criteria is a valid crack; your code need not be similar to the cop's. Here (scroll down) is a list of online sandboxes for testing various regex flavours. ### Scoring Robbers have 7 days to crack a cop's submission, starting from the time it is posted. If a submission is not cracked within this time, the cop should reveal their program; only once this is done will the submission be considered 'safe'. A cop's score will be the length of their regex (not counting delimiters) in bytes, with lower score being better. Only uncracked submissions are eligible for scoring. A robber's score will be the number of submissions they crack. ### Sandbox Consider this challenge a work in progress - I'm finding it hard to gauge how interesting/easy/difficult it might be. Some specific questions: • Is the spec clear/tight enough? • Should the cop be required to reveal their language too, and the robber required to use it? [Yes, to avoid trivial cracks in Lenguage as pointed out by @RedwolfPrograms.] • Should I set a size limit on the regex? (Scoring discourages large regexes, but still...) • Should output be to STDOUT only? • Lenguage could probably trivialize this for any regex with a repeated part – Redwolf Programs Jan 16 at 5:45 • @RedwolfPrograms Thanks, that's a good observation. Edited to require robbers to use the same language as the cops. – Dingus Jan 17 at 0:26 • I think you should explicitly allow/disallow reading the program's own source code – Command Master Jan 19 at 9:30 • @CommandMaster Good idea. I'm leaning towards allowing reading the source code - I think it could keep some interesting possibilities open. Thoughts? – Dingus 2 days ago # Write a Length interpreter Length is a simple stack-based esolang where instructions are encoded as line lengths The instruction set is as follows: Line Length Name Description 9 inp Pushes the ascii value of the first byte of stdin to the stack. 10 add Adds the top two values on the stack and pushes the result onto the stack. 11 sub Subtracts the top two values on the stack and pushes the result onto the stack. 12 dup Duplicates the top value of the stack. 13 cond If the top value of the stack is 0, skip the next instruction. Then pop it. 14 gotou Sets the program counter to the value of the line under the instruction. 15 outn Pops the top of the stack, and outputs it as a number. 16 outa Pops the top of the stack, and outputs its ascii value. 20 mul Multiplies the top two values on the stack and pushes the result onto the stack. 21 div Divides the top two values on the stack and pushes the result onto the stack. 24 gotos Sets the program counter to the value at the top of the stack In case the table doesn't work, here is the esolangs page: https://esolangs.org/wiki/Length Test inputs are too long to put here, they can be found here helloworld.len - Outputs Hello, World! truth.len - A truth machine bottles.len - Outputs the lyrics to 99 bottles of beer This is a code golf, so shortest program wins! New contributor Nailuj29 is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct. • table is broken, it looks fine in preview – Nailuj29 Jan 18 at 20:49 • Fixed. But this should be reported on SE Meta. – Adám Jan 18 at 20:56 # Finish what John McCarthy started (WIP) code-golfinterpreterlisp This does not have anything to do with Joseph McCarthy or communism. Some background from Wikipedia (you can skip ahead if you like): John McCarthy published the first paper on Lisp in 1960 while a research fellow at the Massachusetts Institute of Technology. In it he described a language of symbolic expressions (S-expressions) that could represent complex structures as lists. Then he defined a set of primitive operations on the S-expressions, and a language of meta-expressions (M-expressions) that could be used to define more complex operations. Finally, he showed how the meta-language itself could be represented with S-expressions, resulting in a system that was potentially self-hosting.[3] The draft version of this paper is known as "AI Memo 8".[4] Example M-expressions McCarthy had planned to develop an automatic Lisp compiler (LISP 2) using M-expressions as the language syntax and S-expressions to describe the compiler's internal processes. Stephen B. Russell read the paper and suggested to him that S-expressions were a more convenient syntax. Although McCarthy disapproved of the idea, Russell and colleague Daniel J. Edwards hand-coded an interpreter program that could execute S-expressions.2 This program was adopted by McCarthy's research group, establishing S-expressions as the dominant form of Lisp. # Task Interpret a subset of M-expressions, where 9 primitive functions have already been defined. ## Syntax Atoms: An atom is a series of any characters excluding [, ], ;. While an atom name can include whitespace, leading and trailing whitespace is ignored. Some examples include foo, lambda (also a function name), and nil (also a list). Atoms act as both variables and data (they're like strings). Booleans: The atom t is truthy, whereas the atom nil is falsy. quote: A series of expressions between square brackets, delimited by semicolons. [a; [b; c]; de] is equivalent to the S-expression (QUOTE (A (B C) DE)). It is somewhat like this JS list: ["a", ["b", "c"], "de"]. cond: A series of if-then pairs between square brackets, delimited by semicolons, with an arrow -> (you can use any other character(s)) separating the if-then pairs. e.g. cond[atom[x] -> x; t -> car[x]] yields x if it's an atom, or the first element of x if it's a list. It is guaranteed that at least one of the cases will be true. Function application: Functions can be called using functionname[arg1; arg2; ...; argN]. • car - Return the first element of its argument. • cdr - Return its argument without the first element. • cons - Prepend its first argument to its second argument. • eq - Check if its two arguments are equal. • atom - Check if its argument is an atom. • cond - Takes multiple arguments. Each argument is a list where the first element returns a boolean when evaluated and the second can return anything. It keeps evaluating the first element of each argument until it reaches one that is true. When it does, it evaluates the second element of that argument and returns it. At least one of the arguments are guaranteed to have a truthy first element. • lambda - Define an anonymous function using the syntax lambda[[param1; param2; ...; paramN]; bodythatusesparams]. • label - Store a function using a name. For example, label[drop2; lambda[[xs]; cdr[cdr[xs]]]] defines a function drop2 that drops the first two elements of its first argument. # Rules • Functions may use lexical or dynamic scope, or some crazy mixture of both. Much of this question is copied from this challenge and the Wikipedia article on M-expressions. # Questions for Meta • For cond, should I use the [condition -> res; condition2 -> res2; ...] syntax, or should I keep it like the linked challenge? The former looks nicer, the latter allows one to write an eval function. • Should answers support higher-order functions? • Does anyone have any good examples using Mexprs? • I did a double-take at the title, which sounds like the challenge is to root out communists still hiding in the US state department to finish what Joseph McCarthy started... – xnor 2 days ago • @xnor Uh...that certainly was not what I intended. I could probably say "Finish what John McCarthy started" or just "Interpret M-expressions", although the latter sounds more boring. There's also a Eugene McCarthy, apparently, so I guess just McCarthy is too ambiguous. – user 2 days ago # Print a 3D shape write a program/function to print this cube (or whatever is called) in different sizes:  ^L^L^L^L^L^L^L^L^L^L^L //^L^L^L^L^L^L^L^L^L^L^L ////^L^L^L^L^L^L^L^L^L^L^L //////^L^L^L^L^L^L^L^L^L^L^L ////////^L^L^L^L^L^L^L^L^L^L^L //////////^L^L^L^L^L^L^L^L^L^L^L ////////////^L^L^L^L^L^L^L^L^L^L^L //////////////^L^L^L^L^L^L^L^L^L^L^L ////////////////^L^L^L^L^L^L^L^L^L^L^L //////////////////^L^L^L^L^L^L^L^L^L^L^L ////////////////////^L^L^L^L^L^L^L^L^L^L^L \\\\\\\\\\\\\\\\\\\\ " " " " " " " " " " " \\\\\\\\\\\\\\\\\\ " " " " " " " " " " " \\\\\\\\\\\\\\\\ " " " " " " " " " " " \\\\\\\\\\\\\\ " " " " " " " " " " " \\\\\\\\\\\\ " " " " " " " " " " " \\\\\\\\\\ " " " " " " " " " " " \\\\\\\\ " " " " " " " " " " " \\\\\\ " " " " " " " " " " " \\\\ " " " " " " " " " " " \\ " " " " " " " " " " " " " " " " " " " " " "  The shape is made of pairs of characters: ^L, ", \\, // ### Input: An integer greater than 1 representing the size of the shape. The one showed above has a size of 11 because each side of each face is made of 11 pairs of characters. ### Output: The 3D shape of the given size. Here's another example, with a size of 5:  ^L^L^L^L^L //^L^L^L^L^L ////^L^L^L^L^L //////^L^L^L^L^L ////////^L^L^L^L^L \\\\\\\\ " " " " " \\\\\\ " " " " " \\\\ " " " " " \\ " " " " " " " " " "  This is code-golf, the shortest wins. ## Meta: • Is this clear enough? • Does the challenge fall within Kolmogorov complexity even though an input is taken? • Would be better to remove the input? • Can I call it cube instead of shape? • Should I use a set of more common characters at the expenses of this good looking design? (the original pairs were "¶L", "• ", "\\", "//") • Any other feedback? New contributor Davide is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct. • Suggestion: use characters other than • and ¶ as they are multi-byte characters which not all languages will handle easily. ASCII characters instead would be better – caird coinheringaahing 2 days ago • I modified them, thank you. – Davide 2 days ago • @caridCoinheringaahing I was just looking to try some other character taking as reference this ASCII table. The two characters that I changed are numbers 166 and 167 of the table. I am confused. – Davide yesterday • Most languages can handle code points between 32 and 127 inclusive. Some use custom code pages (e.g. Jelly) that won't necessarily have extended ASCII characters, but will have regular ASCII – caird coinheringaahing yesterday • Oh all right thank you for the clarification! – Davide yesterday • @Davide the table you linked is not actually an ASCII table. ASCII only goes from 0 to 127; there are more code pages that extend it to 256 and the creator of that table has clearly picked one. This confusion arises because almost all code pages include ASCII as the first 128 and then extend with some symbols like ¶ on top of that. Nowadays most things use UTF-8 which encodes some characters with more than one byte and can use millions of different characters from Unicode – pxeger 20 hours ago • @pxeger Oh thank you for this definitive explanation! – Davide 15 hours ago # Radiation Showdown (WIP) Two radiation-hardened programs will go head-to-head to destroy each other. Your task is to create a program which takes the other program's source as input and output the index of the byte that should be deleted from the other program. (zero-indexed) Each program will be radiated at the same time. The first program to fail to return a valid index after being radiated loses (whether by compiler error, runtime exception, out-of-bounds output, or some other means), or it is considered a draw if both fail at the same time. Each program will compete against each other program. The program receives 1 point per round survived. The overall winner is the one with the most points. Programs are limited to a length of 1024 bytes. Alternate possibilities: (Inspired by @Dingus) A hash of the opponent's original source code and a list of the indexes of bytes deleted so far is passed in instead of the current source code, making it a bit more of a blind guess as to what you radiate. If at any time, a program makes a guess it has already made, it loses. This turns it into a sort of "Radiation Battleship" • Interesting challenge. How will it be tested, if different languages are allowed? – user Jan 19 at 19:12 • @user it shouldn't be terribly difficult to make a shell-based controller. Submissions would probably need to include compiler flags or shebangs separately so that the controller knows exactly how to run the program. – Beefster Jan 19 at 19:19 • That would work for "practical" languages, but I'm a bit worried about esolangs. I guess TIO can probably deal with that, though. – user Jan 19 at 19:20 • If Program A has all its bytes deleted before Program B does, does B win? I'm imagining a pathological scenario in which A is empty and outputs by exit code. – Dingus Jan 19 at 23:46 • Also, wouldn't something like this be impossible to beat? – Dingus Jan 20 at 0:12 • @Dingus I suppose that would be impossible to beat. I wonder how I could make things different with resisting arbitrary insertions... probably not viable though. – Beefster 2 days ago • To prevent fixed-output programs, could you perhaps tie the indexing to the unmodified code? In other words, force the output to be different every round? – Dingus 2 days ago • @Dingus I think that might work (implying that both the original program and guesses are passed to the program), but there's probably another similar edge case I'm missing. Kinda turns it into radiation battleship. If a program returns a guess it has already made, it instantly loses. – Beefster 2 days ago • Following that thought, it might be kind of interesting if some opaque id (e.g. a hash of the source code) is passed in instead of the current state of the source code. – Beefster 2 days ago • @Beefster what's the point of the hash? (what can submissions do with it?) – the default. 2 days ago • @thedefault. the hash is only used to assign a distinct id to each program and it could be used to seed a random number generator. – Beefster yesterday • @Beefster I thought submissions aren't supposed to be designed to beat specific opponents (and the only way to use a hash is to optimize to beat specific opponents) (and providing a hash of an unknown string as input just in case somebody wants to seed a RNG with it is a weird decision) – the default. 12 hours ago • Also, if the length of the source code is not known, it's effectively impossible to make guesses that are guaranteed not to be out-of-bounds. (also, I expect 90% answers to this challenge to output something like 0,1,2,3,4,5,...) – the default. 11 hours ago # Find Maximum number of 4+ letter words from Scabble Tiles The challenge is to find the most words with 4 or more letters you can make with one set of scrabble tiles. The tile distribution is as follows: 2 Blank Tiles A 9 N 6 +====+===========+ B 2 O 8 | 01 | K J X Q Z | C 2 P 2 | 02 | B C M P F | D 4 Q 1 | 02 | H V W Y * | E 12 R 6 | 03 | G | F 2 S 4 | 04 | L S U D | G 3 T 6 | 06 | N R T | H 2 U 4 | 08 | O | I 9 V 2 | 09 | A I | J 1 W 2 | 12 | E | K 1 X 1 +====+===========+ L 4 Y 2 M 2 Z 1  Valid words are any words that are 4+ that are available in this file, the official scrabble dictionary. Tiles cannot be used twice. This means you can only have 1 word with a K, J, X, Q, and/or Z unless you use a blank tile to represent one of these letters. I'm not sure how I'd do scoring on this. I want shorter code to score better, but I don't want a short piece of code that finds a lot less words to score better than a longer piece that finds many more words. • Meh. I don't like dependency on external files; are we allowed to load it, or even embed it into the source code? – John Dvorak Dec 17 '13 at 20:00 • as for finding more vs. shorter code, you could demand all words be found – John Dvorak Dec 17 '13 at 20:19 • @JanDvorak Any way to use it. It's a text version of the official scrabble dictionary, it seemed to be the most fitting word list for the task. "All words being found" might be hard, considering there are probably many combinations of words that would deplete all the tiles. It's a maximum of 25 words, (25 words, 4 letters each, 100 tiles), but I don't know if it's possible to use all tiles with just 4 letter words. After so many words, you might not have enough tiles to make an actual word, which means you'd either have to go back or accept that you're not using all the tiles. – Rob Dec 17 '13 at 20:23 • As currently described, this is a no-input task, which means that the answer can be precomputed and then the program only needs to decompress it. Consider rewriting it to take input (either of the word list or of the tiles available). – Peter Taylor Dec 18 '13 at 8:01 • I suggest taking a list of tiles as input, loading the list of words from a predefined file and requiring all combinations / best combination to be found. Of course, if the input is the full list of tiles, the computation is going to take ages. I might allow preprocessing the word list outside the program itself (up to a certain point; a linearithmic growth?) – John Dvorak Dec 18 '13 at 8:32 • I suggest modifying this so that input is a list of tiles, limited to a full rack or less (therefore 4-7 tiles, since our minimum word length is 4). Input should be assumed to be valid based on the standard set of tiles (e.g.: it wont' have something like 3 J's or 4 G's). This would have some practical use for a player in a scrabble game to figure out their next move (though it does not take into account tiles available to them which are already on the board). – Iszi Dec 18 '13 at 21:14 • Alternative mode: Input is a list of tiles, maximum 96 (so that at least 4 are remaining in the set). Output only includes words (minimum 4 letters) which can be created without those tiles. This would be interesting as it provides words that may yet be created (though, again, not taking into account usable tiles on the board) at a given point in the game. – Iszi Dec 18 '13 at 21:15 • Output needs to be decided as either a list of all possible words, or only the highest-scoring word(s). Another enhancement may be to require that the list be sorted descending in order of score (if output is all words), then ascending alphabetically. There's no reason to take each program's output into account for scoring. Since everyone is expected to use the same dictionary, all programs' outputs should be identical (except perhaps in sorting, if that's left out of the spec). So, this should be Code Golf. – Iszi Dec 18 '13 at 21:15 • It's also worth noting that, as currently written, the task could just be to filter the given dictionary down to words which have 4 or more letters. By its very nature, the Scrabble dictionary should already exclude any words that cannot be made with a Scrabble set. – Iszi Dec 18 '13 at 21:18 • @Iszi it's not "what are all the words you can make", it's "what are all the words you can make, where every letter used depletes a tile". There's a max of 25 words if you can use all 100 tiles. – Rob Dec 19 '13 at 16:40 • I think I misunderstood the problem, then. I thought it was "all the words possible using a set of tiles" not "all the words possible, using only one set of tiles". Still, my point about code golf remains. There is an absolute maximum to the number of words (each with 4 or more letters) you can make with a single Scrabble set, and a finite number of permutations which can be used to hit that maximum. Every program written with this goal should end up with the same (or nominally similar) output. – Iszi Dec 19 '13 at 16:56 # Test for Irreducible Complexity (Check for Redundant Characters) I may need some additional help coming up with the full spec for this competition. As of right now, this is just a concept. Many interesting questions, such as the "42" question in this sandbox, involve finding the longest program which is not reducible. This means that no set of characters can be removed and still allow the program to function as desired. The basic idea is that your program will test a Base Program to make sure that it contains no redundant characters. The input will consist of: • Base Program (in the same language as your answer) • Expected Output Your program will simply evaluate all possible subsequences of the Base Program and verify that none of them give the Expected Output. This challenge actually has a utility value to several other challenges. For example, it verifies the results of a "longest non-reducible"-type challenge. In addition, it could make sure that a golfed solution cannot be golfed further. I assume that the winning criteria will be fastest program, as cycling through all the possibilities takes a long time. ## Problems A sequence of length N has 2^N subsequences. Even if each evaluation is done very quickly, it might be unfeasible to test any program with more than 20 or so characters in a reasonable amount of time. • Problem: some subsequences of legitimate answers may be pretty dangerous to the environment. You don't want to eval just everything. – John Dvorak Dec 23 '13 at 16:59 • @JanDvorak Yes that actually is a serious problem. To what extent is it possible to fix that? – PhiNotPi Dec 23 '13 at 17:04 • Forbidding any program with dangerous subsequences? :-) – John Dvorak Dec 23 '13 at 17:05 • A more reasonable (but very difficult) solution would be the requirement to implement a sandbox. – John Dvorak Dec 23 '13 at 17:07 • Even without dangerous behavior, the halting problem will be an issue: it's hard to tell whether a shortened program will terminate at all, especially for every conceivable input. – MvG Jan 7 '14 at 23:49 # Popularity Contest: Implementation of a Hash Table Create a class in some OOP language for a hash table that supports getting, setting, and removing values. You can't use the built in hash table/dictionary/map implementation. Highest votes in one week wins. A key is any valid string. A value is any valid string, number, or boolean. Example functionality: hash.set("key","value"); hash.get("key"); // returns "value" hash.set("key", 1234); hash.get("key"); // returns 1234 hash.set("key2",hash.get("key")); hash.get("key2"); // returns 1234 hash.delete("key"); hash.get("key"); // returns null/undefined/none/etc. or throws an error hash.get("key2"); // still returns 1234  Definition of a hash table (from Wikipedia): In computing, a hash table (also hash map) is a data structure used to implement an associative array, a structure that can map keys to values. A hash table uses a hash function to compute an index into an array of buckets or slots, from which the correct value can be found. The hash table cannot be simply an array that is searched in linear time. It must be an actual hash table that uses a hash function to map the keys to the value. • Popularity contest and shortest don't mix. That aside, the spec is too vague. What is a "value"? What assumptions can be made about hashcodes? If the language makes all types nullable, should null be permitted as a key? What should the type be in languages which have co- and contravariance? And for that matter, what qualifies as a "hash table", bearing in mind that people will try to exploit any loophole? – Peter Taylor Jan 2 '14 at 23:16 • @PeterTaylor Thank you for the feedback! Please see my edits, and let me know what you think. Could you meant about co/contravaraince? I looked at the wikipedia article about it but I'm not really sure how that has anything to do with this question. – hkk Jan 2 '14 at 23:37 • I think it's still vulnerable to the loophole of "I have a hashtable with one bucket" (i.e. it's really a list of (key, value) pairs which I traverse in linear time). The thing about variance is to do with static typing of the elements of the map. E.g. in Java Map<String, Integer>'s get method has signature public Integer get(Object); in C#, a Dictionary<string, int>'s Get method has signature public int Get(string). The edited version makes it clear enough that the hashtable isn't expected to be genericised. – Peter Taylor Jan 3 '14 at 0:08 # Wordlist detector You are to write a program which, given a list of words, constructs a regular expression to match all these words but nothing else. Both your program and the constructed regular expressions are to be as short as possible. ## Input and Output Input comes on standard input and consists of one line giving n, the total number of words, followed by n lines with one word each. The number of words will be less than 1000, the length of each word less than 30. Words will consist only of lower case ASCII letters, i.e. a-z. You may choose to ignore the first line and use EOF instead to end the list. Output shall be written to standard output. It consists of a single line, giving a POSIX extended regular expression to match these words and no others. Since input for this regex is not restricted to letters only, elements like . or [^…] won't make too much sense, which limits the language in a natural way. You may choose whether you want to terminate the line with a newline or not. Programs may choose to print multiple lines of output, in which case only the last one will be used for scoring. So you might print intermediate results and continue searching for improvements. ## Test cases Each submission may be accompanied by one regular expression. When scoring the submissions, I'll use this regular expression to reconstruct a word list from it. The code to do this reconstruction can be found at the end of this post. The reconstructed word list must fit the input specification above in terms of word count and length. It would be nice if your own program would be able to regenerate that regular expression from the word list, but that is not a strict requirement. But please don't paste bogus programs just to submit a challenging regular expression, though. These test cases will be collected and fed to all programs for scoring. ## Scoring The final score of each program will be the program size plus the size of all its generated regular expressions for the inputs collected from submitted answers, including the example from this question. So short code which produces too long results might get beaten by longer code which generates shorter expressions. Does this still qualify as ? Submissions which generate an incorrect regular expression for one of the test cases will be disqualified, as will those which don't terminate in the allotted time. You can use the input reconstruction program below to check whether a produced regular expression does encode the correct word list. ## Requirements All submissions are welcome, but in order to include your submission in the tournament, it must be executable with reasonable effort on my Linux machine. It shouldn't depend on any exotic libraries, or any specialized ones which take too much work away from your own program. It must operate in reasonable time, say no more than five minutes per input. Your output must be reproducible, so if you use randomization at some point, please seed the randomizer, and please don't terminate an improove loop by a timer measuring execution time or some such. ## Tournament times I'll run the first major tournament two weeks after posting this question. I'll include a table of the results in this question. I'll try to run tournaments repeatedly as late submissions arrive, but I'll not promise any regular schedule. ## Example An very simple example application would be in Python 3 (53 chars): print('|'.join(input() for i in range(int(input()))))  And here is a test case which could be posted along with the program, although this program obviously doesn't generate exactly this concise output: bann?ana|ap(fel|ple)|s[ou]n|[hs](a|ou)nd  The expansion of that expression could be turned into the following example input, which need not be posted as part of an answer since it can be deduced from the regular expression: 10 banana bannana apfel apple son sun hand hound sand sound  ## Regex expander program And here is a program to turn regular expressions into word lists, again written in Python 3. #!/bin/env python3 concat = set(('',)) altin = set(('',)) altout = set() prev = None stack = [] regex = iter(input()) for ch in regex: if ch == '(': stack.append((concat, altin, altout)) altin = concat altout = set() prev = None elif ch == ')': concat.update(altout) prev, altin, altout = stack.pop() elif ch == '|': altout.update(concat) concat = altin elif ch == '[': ch = regex.__next__() cls = [] while ch != ']': if ch == '-': crange = range(ord(cls[-1]), ord(regex.__next__()) + 1) cls.extend(map(chr, crange)) else: cls.append(ch) ch = regex.__next__() prev = concat concat = set(w + c for w in prev for c in cls) elif ch == '?': concat.update(prev) prev = None elif ch >= 'a' and ch <= 'z': prev = concat concat = set(w + ch for w in prev) else: raise Exception("Illegal input") if stack: raise Exception("Unclosed group") concat.update(altout) words = sorted(concat) print(len(words)) print('\n'.join(words))  This is restricted to the part of regular expression syntax which I expect for this answer. If you have good reason to use something I did not consider, feel free to do so although I will likely have to update this code to cope with it. If you find a bug, please let me know. • This is just Meta regex golf under the constraint that the two lists between them cover all possible words. Given that some people are tackling that existing question on that basis, this would qualify for closing as a duplicate. – Peter Taylor Jan 8 '14 at 8:45 ## Code-Golf: Write a number as an expression that's as short as possible The goal of this code-golf is to create a program that takes a number as input (using STDIN, command line arguments, or prompting for input), and outputs that number, but written as an expression that's as short as possible. So, 10000 should become 10^4. If there is no way to write an expression that's shorter than the number, then output just the number. ### Other rules 1. No network access. 2. You're not allowed to execute an external program. 3. Only use the operators +, -, *, / and ^ (that's raising power, not XOR). 4. Order of operations must be taken in account. Use parentheses if necessary. 5. This is a code golf, so the code with the smallest amount of characters wins. 6. The input will always be smaller than 2^32. ### Test cases 500000000 --> 5*10^8 or 10^9/2 999999 --> 10^6-1 10 --> 10 4294967295 --> 2^32-1 16384 --> 2^14  ## Rhymalator (at the point, it's just something that came to me before i wake up, so it may need some adjusting, and i'd like some feedback as to if this could be fun) The code challenge is to write a program that takes as input a calculation in Reverse Polish Notation and outputs the result. It must at least implement + - * /. It So far so easy, but to make it fun and "artistic", the following restriction applies: • The source code must rhyme when read. Example in PHP $iterator = str_split($a); foreach ($iterator as $key=>$value){
if ($key > 3){ ++$virtue;
}
}


(the rhyme is on value-virtue)

• Lines whitout readable characters count as whitespace (the two lines with } in the example)

• How does that example rhyme...? – Doorknob Jan 25 '14 at 12:54
• @DoorknobofSnow well, i'm not really a poet, that's why i propose it as a challenge for others :p. if you have a better example i'll replace it – Einacio Jan 27 '14 at 15:58

# Implement Kalah code-golf

The game of Kalah is a two-player board game in the Mancala family. Your implementation must:

• Identify the active player ("Player 1" or "Player 2")
• Display board state (in format specified below)
• Accept input to allow that player to move (using index system below)
• Announce a winner ("Player N wins")

# Overview

Each player has a line of six spaces, called houses, and one additional space called a store. Each space holds seeds, which move from house to house in a counter-clockwise direction. The objective is to fill your store with seeds.

You must represent the board in the following two-row format with stores offset, where HH is a house and SS is a store:

SS HH HH HH HH HH HH
HH HH HH HH HH HH SS


The top row represents the number of seeds in player #1's spaces, and the bottom row represents the seeds in player #2's spaces. The S in each row is the respective player's store (player #1's is top-left, #2's is bottom right). Single-digit values should include a leading space.

In this challenge, user-input will identify each house numerically. Use a left-to-right, indexed-from-one scheme for both sides:

S 1 2 3 4 5 6
1 2 3 4 5 6 S


Note that the players' stores are not numbered, because seeds placed in the store never move out.

## Rules

Wikipedia has a good summary of the game and its rules:

1. At the beginning of the game, three seeds are placed in each house.

2. Each player controls the six houses and their seeds on his/her side of the board. His/her score is the number of seeds in the store to his/her right. [Clarification: from our perspective, player 1's store is to the left, player 2's store is to the right.]

3. Players take turns sowing their seeds. On a turn, the player removes all seeds from one of the houses under his/her control. Moving counter-clockwise, the player drops one seed in each house in turn, including the player's own store but not his/her opponent's.

4. If the last sown seed lands in the player's store, the player gets an additional move. There is no limit on the number of moves a player can make in his/her turn.

5. If the last sown seed lands in an empty house owned by the player, and the opposite house contains seeds, both the last seed and the opposite seeds are captured and placed into the player's store. [Clarification: moves that end on an opponent's empty house end normally without a capture.]

6. When one player no longer has any seeds in any of his/her houses, the game ends. The other player moves all remaining seeds to his/her store, and the player with the most seeds in his/her store wins.

# Example

(Parenthetical text should not appear in actual output.)

Player 1
0  3  3  3  3  3  3
3  3  3  3  3  3  0
> 2                      (prompt arrow and line break
are purely optional)
Player 2
1  1  0  3  3  3  3
4  3  3  3  3  3  0
> 4

Player 2  (P2 gets a bonus turn from rule #4)
1  0  3  3  3  3  3
4  3  3  0  4  4  1
> 5

Player 1
1  0  3  3  3  4  4
4  3  3  0  0  5  2
> 4

Player 1  (P1 captures P2's seeds in space 1)
6  0  4  4  0  4  4
0  3  3  0  0  5  2
...

Player 2
12  0  0 10  0  1  0
0  0  0  0  0  1 13
> 6

Player 1 wins            (because the non-finishing players gets
all remaining seeds on their side, it's 23-14)


Meta question: Would this be improved by removing some of the rules?

• Do the players run the game once and then take it in turns to take moves, with the process ending only when the game ends? Or do they run the program once per move? – Peter Taylor Jan 30 '14 at 10:06

[This is the first time I'm using the sandbox. I want to get feedback/suggestions before posting the question.]

Make a spider web (standard, orb type) that fills frame in the ratio of n:m, where n, m are input integers. You may use the example below as a model (but you don't need to use labels).

Your web should have multiple radii, at least 4 of which attach directly to the frame. The remaining radii should attach to the outer outline (perimeter) of the web. The web should have at least 15 radii. The mesh spacing should be more or less uniform spacing (although occasional weaving mistakes" or crossings are encouraged and will receive a bonus).

This is code-golf, so the shortest code (minus bonuses) wins.

Bonuses (to be removed from the number of characters in your code). Bonuses are awarded for the following features that reflect the architecture of an actual web (as opposed to a perfectly symmetric rendering). They are somewhat greater than usual as an incentive for attention to detail and realism.

-mesh spiral instead of concentric circles: 40 pts

-assymmetric web: 31 pts. (e.g. height of capture area greater than width)

-distinct segments between radii (straight or crooked, but not the arc of a circle): 32 pts

-outer and inner outline clearly distinct from the spiral: 41 pts

-irregular outer outline: 20 pts

-2 or more easily observable reverses in spiral: 40

The accept will be awarded on Feb. 20, 2014.

• If there are bonuses then it isn't code-golf, by definition. It's not clear what output formats are acceptable. I'm not sure what you mean by "distinct segments between radii". "2 or more easily observable reverses" seems problematic: the ease of observing reverses is subjective, and might in addition depend on input and/or on the random numbers obtained. The weighting for the bonuses seems very arbitrary: is there any justification for it? – Peter Taylor Feb 3 '14 at 11:49
• Re: bonuses, I should probably decide on the features I want included in the web, thereby eliminating bonuses altogether. Distinct segments means that there should be 2 straight mesh segments between radius n and radius n+2 (not sure whether this should be required in instructions to be updated.) Will give reverses more thought. – DavidC Feb 3 '14 at 12:02

## Write a PHP Code Golfer code-challenge

Since my currently daily programming is in PHP, I tend to try the challenges on the site using that language, but frequently I large program because of the verbosity of the language. And then I have to strip it for presentation...

But this is not a tips question, it's an eviscerating challenge.

The objective is to write a program in the language of your choice that takes a PHP file and outputs a golfed valid PHP file with the same functionality.

The scoring will be the average reduction in percent of the result of running the program with 3 selected files (not yet selected, I was thinking of some open source library)

The output file should run on at least 5.4 (so shorthand arrays, function dereference, traits are available)

Since the score is the difference between the ungolfed and golfed files, techniques beyond minifying are encouraged, such as using code subtitution, eval, compression,  (variable variables), dereferencing...

Scoring example: The 3 sources have 450, 1200 and 3500 chars respectively

results lenghts: 250, 1000, 3300
reduction: 200, 200, 200 (44%, 17%, 6%) average: 22%

results lenghts: 350, 1050, 3150
reduction: 100, 150, 350 (22%, 13%, 10%) average: 15%

In this case Answer 1 would win, even tough both answers got the same total reduction (-600 chars)

• It's a specialisation of codegolf.stackexchange.com/q/3652/194 , so would likely be closed as a duplicate. – Peter Taylor Feb 4 '14 at 22:44
• @PeterTaylor I saw it. is similar, but I include an objetive goal and score. have any idea on how to make it more unique? – Einacio Feb 5 '14 at 2:43
• "Making it shorter" is too broad, can I just delete some comments? If not, can I only shorten one variable and it's ok. It's not very interesting like this... – Fabinout Feb 5 '14 at 9:56
• @Fabinout the objective is golfing the code. If you only remove some characters, I doubt you'll get a good score – Einacio Feb 5 '14 at 15:27
• Alright, the criterion is the size of the output source code. good clarification. – Fabinout Feb 5 '14 at 15:55
• Sum the bytes with the percents or separately? Also, no matter what sources you choose, make sure to paste the code into your questions; who knows when the code in the library will change? – Justin Feb 6 '14 at 19:11
• i'll edit the bit about scoring (with examples) tomorrow (when i come back to work). I'll post the test sources as a pastebin, but I'll wait to choose them until the question is polished enough and someone consider it interesting enough – Einacio Feb 6 '14 at 19:34
• Is there anyone more with questions? is still possible that it will be marked as a duplicate? or can i choose the sources and publish it? – Einacio Feb 13 '14 at 19:22

# Create diagonal code

Your task is to create a program that outputs d=s*sqrt(2).

Specs:

• Your program must be at least 4 lines long;

• d=s*sqrt(2) cannot be hardcoded as is (so using ascii, compression, encoding, etc. is allowed and encouraged);

• For each line of code n, pick up the nth character. The string obtained this way must be a valid program in a programming language of your choice, that must be different from the one you used for the main program. The obtained program must compile successfully, but it can throw errors, exceptions, etc.;

• If at the nth line there is no nth character, you can consider that character as a whitespace or a newline. This cannot be done for the first 4 lines, which must be long at least n non-whitespace characters.

• Your main program must end successfully (no errors, exceptions, etc.);

• Internet access is forbidden;

• Most upvoted answer in 2 weeks wins.

Happy coding!

I was unsure about making this a with several bonuses (polyglot answer, secondary program still valid, etc...).

### Some bonuses for the code-challenge version:

+15 for any other hidden answer;
+5 for every hidden answer that runs and ends successfully, without any problem;
+15 for every hidden answer that is a polyglot;

Which version would you prefer? Is there something you would change/improve in this question?

I personally like the one, but the KISS principle (Keep it simple, stupid!) reminds me that I may be wrong.

• It's trivial to make the diagonal program be just whitespace (many scripting languages will accept this as a program) or H  (valid program in H9Q+). – Peter Taylor Feb 26 '14 at 9:26
• Nowhere does it say that the diagonal program must output your magic string: it doesn't even have to execute correctly. Your amendment doesn't really fix things: I can now have the second line be #H, the third be #HH, etc. – Peter Taylor Feb 26 '14 at 9:37
• You're right; Don't know why, on a second read I messed up the meaning of your comment. Anyway, I suppose this excludes code-challenge unless I/we don't find a way to avoid such trivial solutions. I guess popularity-contest would still be ok, since more interesting solutions could be found, right? – Vereos Feb 26 '14 at 9:41
• I think my views on popularity-contest in general are well known. On further reflection, there are enough languages in which any string of bytes is a valid program that I don't think this question can work as is. If you want to save it, I think you need to look at doing something like a very difficult double-quine. – Peter Taylor Feb 26 '14 at 9:49
• Thinking about quines and diagonals (which was the "spirit" of the question), what about a sort of mini-quine? The main program would have to display d=s*sqrt(2) only, and its diagonal must reproduce the code used to display the magic string (no comments allowed). It could be tagged code-golf or code-challenge. – Vereos Feb 26 '14 at 11:04

# Create a Karnaugh-map calculator

Given an input of a truth table, generate a corresponding K-map.

Input:

Input will be of the form 10110001 where each bit is a row of a truth table. Count from the left to the right; so that input would be a table of:

i2i1i0 f
0 0 0|1
0 0 1|0
0 1 0|1
0 1 1|1
1 0 0|0
1 0 1|0
1 1 0|0
1 1 1|1

Max 4 variables will be inputted

K-maps (a small explanation):

K-maps are a way of simplifying boolean-algebra expressions.

Let's say we have 4 variables: a, b, c, d. Let the truth-table be 1110101001111111 (and the columns on the truth table be labeled, from left to right: a, b, c, d). Arrange the variables like so:

   cd
ab\   00 01 11 10
00
01
11
10


Note the grey-code counting scheme.

Fill in the table with the corresponding values from the truth table:

   cd
ab\   00 01 11 10
00 1  1  0  1
01 1  0  0  1
11 0  1  1  1
10 1  1  1  1


Group the values in rectangles whose dimensions are the largest possible powers of two. Note that this table signifies a torus, so wrap over the left and right edges.

The expression for the truth table is the ors of the and of the unchanging elements. For this, that would be:

Purple group: ¬b ∧ ¬c (for 0's, make them 1 by notting the value)
Green group: ¬a ∧ ¬d
Black group: a ∧ d
Blue group: b ∧ ¬d

Expression: (¬b ∧ ¬c) ∨ (¬a ∧ ¬d) ∨ (a ∧ d) ∨ (b ∧ ¬d)

Output:

• Generate a 2D K-map (for more variables, add on either side) and show the grouping. K-map must be of the form I used. For less variables, remove rows or columns and change the list on the top left corner.
• assume alphabetical ordering on the variables, that is, the first variable is a, second: b, third: c, and so on.
• Also show the expression. Rather than use the unicode characters, the following is permissible:

~ instead of ¬


Edit: Possible duplicate: More fun with gates: Karnaugh simplification

• I think the grouping is not unique and therefore I might choose the most basic grouping (i.e. none). – Howard Feb 26 '14 at 9:02
• Although @Howard's concern is partially answered by "rectangles whose dimensions are the largest possible powers of two", it's not obvious to me why you haven't also circled the entire row 10 and the bottom-right quadrant. – Peter Taylor Feb 26 '14 at 9:29
• @PeterTaylor You're right - didn't read that line. But still my main concern is correct: it is not unique. Or as your remark shows it is not optimal if you choose all rectangles. – Howard Feb 26 '14 at 9:33
• Also for higher number of variables you have to either go to n dimensional K-maps or you won't find all possible rectangles (they are no longer adjacent in the matrix). – Howard Feb 26 '14 at 9:38
• @PeterTaylor In priority: Biggest rectangles, then least number. That is a big rectangle, but it is redundant with the others because every 1 in it is already circled. – Justin Feb 26 '14 at 16:44
• @Howard Good point. I'll restrict it to 4 or less variables. – Justin Feb 26 '14 at 16:47
• For the expression: rather than using A and V, why not * and +? That's fairly conventional use of field notation to represent GF(2). – Peter Taylor Feb 26 '14 at 17:11
• Ahem. OR is, of course, not the same as + in GF(2). But * and + is still the conventional notation for operations over the Boolean semiring. – Peter Taylor Feb 28 '14 at 15:31

Title: Implement ROT-13... in ROT-13

Content:

Challenge: Implement ROT-13 in code that works as both itself and as the ROT-13 version of itself.

### Scoring:

Your score is calculated as a percentage of used, ROT-13 eligible bytes in total of both versions of the program divided by total bytes (all characters) of both versions.

A used, ROT-13 eligible byte is any character that is not part of a comment or ignored by the compiler/interpreter. For example, any character in a brainfuck program that is not +-<>[],.  is not considered a used byte, and any character in a C program including and after // or inside /* */ is not considered a used byte. All special symbols in APL are not considered used, as are all characters in a Whitespace program (sorry).

Example scoring:

### C: 21/32 = 65.625%

main(){printf("Hello World!");}

• Originally this question was ROT-47, not ROT-13. The rules are chosen so that choice of language doesn't easily determine the winner; otherwise, whitespace would easily win. When I changed it to ROT-13 I made only [A-Za-z] count so that a language like golfscript or brainfuck would not automatically score 100%. Looking for thoughts on how to capture the idea without making it too "choice of language" dependent. – durron597 Mar 3 '14 at 21:13
• Just saying, I have a C answer for the 47-version: qp.mniip.com/p/tz pick either of the lines – mniip Mar 3 '14 at 21:29
• @mniip Okay I undeleted it :) – durron597 Mar 3 '14 at 21:48

# Convert input to ASCII Semaphore

With monitor resolutions getting higher and font sizes getting lower, a good programmer has to make efforts to ensure that output is accessible to the visually impaired. This can be problematic when the only display is in text. Toward this end, your assignment (if you choose to accept it) is to write a program that converts text input into ASCII art flag semaphore.

## Input

1. Your program must accept any letter in the ASCII character set from A to Z (case insensitive) and spaces.
2. The program can accept input in any way that is convenient for the language it is written in (stdin, command line, file, etc.).

## Output

1. The program should output an ASCII art representation of the input string in flag semaphore. Follow this link to see the expected encoding.
2. Line feeds and carriage returns should be interpreted as spaces.
3. Numbers and other non-letters in the input may be ignored.
4. You may use whatever ASCII art representation of the semaphore sender you like, but it must contain a person holding two flags and have distinct arms, legs, head, and flags. It must be at least 10x10 characters.
5. Output may be either horizontal or vertical.

## Example

Input: Hello

Output:

           ###
###
#
_____########
|  |       ###
|__|      ####
# ###
#  ###
/   # #
/\   # #
/  \  # #
\  /  # #
\/  ## ##
/\
/  \
/\  /
#  \/
###  #
### #
# #
####
# ###
# ###
# ###
# ###
| # #
|__ #
|  |#
|__|#
## ##
/\
/  \
/\  /
#  \/
###  #
### #
# #
###
####
# ###
#  ###
#   ###
/    # #
/\    # #
/  \   # #
\  /   # #
\/   ## ##
/\
/  \
/\  /
#  \/
###  #
### #
# #
###
####
# ###
#  ###
#   ###
/    # #
/\    # #
/  \   # #
\  /   # #
\/   ## ##
/\
/  \
\  /\
\/  #
#  ###
# ###
# #
_____########
|  |       ###
|__|       ###
###
###
# #
# #
# #
# #
## ##


## Scoring

This is code golf. Shortest code wins.

• define "easily recognisable". Would a simple 3x3 compass (say, with a head if not covered) do? say:.o. -|. /|. ; or even: ... xx. x.. (read by lines, dots represent spaces) – John Dvorak Mar 6 '14 at 20:16
• @JanDvorak Good catch. Edited to include distinct items that must be present and a minimum size. I'm not exactly sure how to make that rule more clear. – Comintern Mar 6 '14 at 20:34
• Define "person holding two flags". Is what I drew a person? Is this a (lying, due to formatting issues) person: o--? Are three x's on a vertical line a person? – John Dvorak Mar 6 '14 at 20:43
• @JanDvorak Ack! had to many tabs open and forgot to save my edit. I think number 4 for output should cover that. – Comintern Mar 6 '14 at 20:47
• Define "distinct arms, legs, head, and flags." But I suggest allowing very small figures as well, otherwise this will turn into a kolmogorov-complexity-like question with very little of the code actually involving generating a pair of directions. – John Dvorak Mar 6 '14 at 20:51
• Very similar to this question. The ascii art is more complex here so perhaps it's not close enough to be called a duplicate... – Gareth Mar 6 '14 at 22:20
• I disagree with @JanDvorak: I think this would be better with a fixed output spec which must be followed exactly. That way people can golf their code rather than the output. – Peter Taylor Mar 6 '14 at 23:59
• Standard figures seem best to me as well. If you demonstrate a full "clock" of hand positions for the standard figure, then you can require those as output. That's easier to assess than free reign for variations. – Jonathan Van Matre Mar 7 '14 at 0:14

With its strange choice of 9 different characters (plus space and newline), the ASCII art version of the FreeBSD logo has always looked to me as if it might be nicely formatted, obfuscated code is some programming language. (Is it?)

 
s .....---.......--.   -/
+o   .--         /y:      +.
yo:.            :o      +-
y/               -/   -o/
.-                  ::/sy+:.
/                     --  /
:                          :
:                          :
/                          /
.-                        -.
--                      -.
:                  :
.--             --.
.---.....----.


Therefore I would like to challenge you to make it one: Either specify minimal changes to an existing programming language or minimal changes to this piece of ASCII art (making the artwork look different or significantly changing the character set used are definitely major changes), so that the logo, as source code generates meaningful output.

This should be a challenge, although I wouldn't mind some way of introducing hard scoring and run this as .

## King of the Hill Fighting

In this game, a player controls 5 bots that attack the other players 5 bots. Each bot has life points, and has to reduce the other playres lifepoints to zero. This post is program that tests the controllers. It is in literate haskell.

> import Data.Set as S
> import Data.Map as M


Here is the arena:

    D---G
/|   |\
B |   | J
/|\|   |/|\
A | E---H | L
\|/|   |\|/
C |   | K
\|   |/
F---I
20  12    4
16    8   0


Positions are denoted by letters

> data Positions = A | B | C | D | E | F | G | H | I | J | K | L deriving (Show, Read, Eq, Ord)


Each player is presented a map in which their side is the one with A. Here is code that will reflect it so each player sees their own view.

> pairFlip = (\(x, y)->[(x,y), (y,x)])
> reflect = M.fromList $[(A,L), (B,J), (D,G), (C, K), (E, H), (F, I)] >>= pairFlip  Lines denote connections. > connections=S.fromList$
>   [(A,B), (A,C), (B,D), (C, F), (E, D), (E, F), (D, G), (E, H), (F, I)]
>   >>= pairFlip
>   >>= (\(x,y)->[(x,y), (reflect ! x, reflect ! y)])
>
> connected x y=(x, y) S.member connections


The numbers below are the number of life points of generation that each bot.

> regen = M.fromList $> [ (A, 20), (B, 16), (C, 16), (D, 12), (E, 12), (F, 12) > , (G, 8), (H, 8), (I, 8), (J, 4), (K, 4), (L, 0)]  • Is there supposed to be a specification hidden in here somewhere? – Peter Taylor Mar 14 '14 at 16:30 • @Peter Taylor Just not done yet. – PyRulez Mar 14 '14 at 16:44 • You won't get lots of answers if it's limited to Haskell. – ugoren Mar 14 '14 at 17:57 • No no no, the above post is also a program for testing it. I will add in code that can take arbitrary programs and use them. – PyRulez Mar 14 '14 at 21:17 # music theory challenge Create a program that takes some input in the form of frequency, waveform, and duration that generates an audio stream based on the input. You can take input parameters however you choose, but if I input (translated to your method) 440Hz, sin(x), 3 seconds, your program should play or create a file for a sound 3 seconds long at 440 hertz on a sine wave. Also, any output should be musically correct as far as frequency is concerned. See http://www.phy.mtu.edu/~suits/notefreqs.html for example frequencies Since this is a popularity contest, the rest is up to you. I bid you Good programming! Oh, and any use of external functions or APIs is ok, as long as they weren't developed specifically for this contest. • If the program takes "input in the form of frequency, waveform and duration" then where do linear functions fit? What do you mean "output should be musically correct as far as frequency is concerned" given that the input is frequency? Is it supposed to correct the input: "You said 494Hz but you must mean 493.88Hz"? And simple synth has been done before in various guises: see music. To differentiate this and make it non-trivial you could perhaps specify a set of basic synth operations which need to be configurable (e.g. input specifies generators, envelopes, filters, mixers). – Peter Taylor Mar 14 '14 at 8:39 • On second thoughts, that would probably work better as a Code Review Code Challenge – Peter Taylor Mar 14 '14 at 9:23 • @PeterTaylor I didn't even know about Code Review Code Challenges <intrigued>. Linear isn't the right word...and I think that statement is redundant anyway, so I'll nix it. – David Wilkins Mar 14 '14 at 12:44 • Actually, I'm going to re-write this challenge...I don't know yet whether it'll be here of on CR – David Wilkins Mar 14 '14 at 13:07 ## Calculate pi using a unique method Your task is to calculate or approximate pi using the most interesting method you know. Well-known things such as using inverse trig functions (asin, acos, atan) or commonly used convergent series are considered uninteresting. You may calculate pi to any precision desired, but the more precision you can achieve, the better. • I couldn't find an exact duplicate of this, but I'd like to know if this overlaps too strongly with an existing question. – Kendall Frey Mar 14 '14 at 18:51 • If you rule out convergent series, what's left? – Peter Taylor Mar 14 '14 at 20:02 • @PeterTaylor If someone knows of a convergent series that isn't on Wikipedia, that would make a good answer. I know of an answer that does not use trigonometry or an approximation, but calculates the digits directly. – Kendall Frey Mar 14 '14 at 20:08 • Is it in mathworld.wolfram.com/PiFormulas.html ? I've got some ancient code which uses a spigot hypergeometric evaluator to compute pi as 3*F(1/2, 1, 1, 8/5 ; 3/5, 4/3, 5/3 | 2/27), but I would expect that to count as well-known. – Peter Taylor Mar 14 '14 at 20:11 • @PeterTaylor I'm familiar with it in layman's terms only, but I don't see it there. It could be related to some of them, but I don't see more than a small resemblance. It isn't original with me, BTW. – Kendall Frey Mar 14 '14 at 20:22 # I like trees ...so this is a challenge to make me a tree. Produce a program called tree which takes a single integer argument, N and draws a randomly-generated tree N levels deep, where level 0 is just the trunk. • Your program must produce visibly different results for at least N=0..5 • The tree ought to not be symmetrical in any axis. • The tree should be an image • Tree(5) should mostly fill dimensions of at least 200w*250h • I should be able to run your tree from a bash prompt, eg. '$ python tree.py 3'

I also accept ferns.

Optionally your tree may be 3d, iterate forever, be colourful, have leaves at level 5, or be lit according to the time of day. However, this is code-golf, so the smallest file wins.

Tags: code-golf

# Implement multi-line lambdas in Python.

Guido van Rossum said it couldn't be done, prove him wrong. Your solution should allow multi-line anonymous functions, like:

>>> f = multilinelamba("hour", """
...     if hour > 20 or hour < 6:
...         print "Good night"
...     else:
...         print "Hello world"
...     """)
>>> f(10)
... 'Hello world'


Your solution should be as close as possible to the behavior of real def or lambda. The actual syntax doesn't matter. E.g. you may choose to pass the code as a string as above, or you may find a way to avoid it. The implementation is also open, you may for example define a function, write a preprocessor, or edit the python source, but keep in mind that the solution should fit in the answer, so the last option probably won't work.

Your solution must allow arbitrary python code inside, except the following which is optional:

• recursive use of the multilinelambda "statement" inside of the multilinelambda
• calling the function recursively, i.e. using f inside the multilinelambda in the above function
• defining classes and
• importing modules (these two might be too hard)

You must also be able to use a multilinelambda as a parameter when calling a function.

You get bonus points:

• If your solution captures outside variables in a closure, like real def does
• For correct handling of exceptions in the multilinelambda. They should display similarly to when using def, and include line number relative to the file.
• For allowing default parameters
• For allowing *args and **kwargs
• If the solution admits any kind of consistent indentation. Two options must be considered:

• All lines have a common indentation (like in the example above) that can be stipped away.
• The first line of the body is given on the same line as the multilinelambda statement. In this case, all the remaining lines must be checked for consistency. It makes a difference whether the first line starts a block or not. Example:

multilinelambda("x", """print "Hello"
print "World" """)

multilinelambda("x, y", """if x > y:
print "case 1"
else:
print "case 2"
""")


In both cases, I may add or remove the same number of spaces to/from each of the lines following multilinelambda.

Any ideas for additional criteria? I personally don't really care much about picking a winner, this is more about tinkering and proving that it can be done. But in any way, more "unit tests" will only benefit the question.

Foreword: This might have been done before, but I couldn't find any such cases. I think the scoring is quite fair now, and the challenge quite clear, but any criticism is welcome. Only thing I am not sure of (besides maybe a similar question existing) is whether it is rewarding enough to add a single language or whether a 2 byte solution which just runs in two languages is going to win (is that possible?).

# The challenge

Write a single piece of code that will only output different deterministic integers depending on the language it has been interpreted as.

# Scoring

Length of the code divided by the multiplication of the score of every used language. Esoteric languages have score 2 and production languages have score 3. For example, if you have a code of length 120 which runs in whitespace and javascript this will give a score of 120/(2*3)=20.

# Rules

• Versions and forks: Different versions and forks may count as different languages, provided that the output is not determined by the version or similar constants in any way. In other words: <?=intval(phpversion())?> or 1<!--[if IE 8]>1<![endif]--> is not allowed.
• The outputted integer should be the constant and only dependent on the language it is run in.
• Only the most common compiler for a language should be used.
• The code should output nothing besides the integer.
• No two interpretations (languages) of the code may yield the same integer.
• In cases where there is any serious discussions of a language being esoteric, it will be counted as esoteric if no commercial company with at least 50 employees can be pointed to developing it's main product in the discussed language.

^ Blame the sandbox for that last crazy over specific rule

• Define "esoteric." Also, the last time is fairly opinion-based. And what about different versions of the same language? Or similar languages (i.e. C and C++)? – Doorknob Mar 22 '14 at 21:40
• Yes, a two-byte solution which runs in two languages is arguably possible. The arguments will come around things like what precisely you mean by "output ... [an] integer". Is additional non-numeric output (punctuation, ans - , or the like) permitted? If so, can the integer be part of an error message from the interpreter? Also expect arguments about whether languages are esoteric or production: it's clear-cut for C and Piet, but there are plenty of languages in much greyer territory. – Peter Taylor Mar 22 '14 at 23:30
• @Doorknob: Added a link and a rule regarding esoteric. Addressed the issue regarding forks and versions. – David Mulder Mar 23 '14 at 0:27
• @PeterTaylor: Great point regarding additional output! Would you have an example of a language you would consider to be gray? I added an additional note regarding the esoterism, but would like to have a 'gray' language to see whether the added rule would make a clear cut or still keep it gray. – David Mulder Mar 23 '14 at 0:29
• "Major/generally known" is highly opinion-based... – Doorknob Mar 23 '14 at 0:31
• @Doorknob: Although programmers do tend to think that anything a computer can not parse is opinion based, it is not hard to draw a line there knowing any of the social sciences, but fair enough, let me change that to a something even a programmer is able to comprehend. – David Mulder Mar 23 '14 at 0:38
• Okay, seriously, now you're just being ridiculous. The reason an objective specification is needed is because two people might disagree with the interpretation of the rule. – Doorknob Mar 23 '14 at 0:45
• The grey area I was thinking about is mainly functional languages. Common LISP, Haskell, OCAML, and F# all see some serious use; I'm not sure whether any of them meet your updated criterion. I can also report that a two-byte solution which runs in two languages is possible, but wouldn't win: I've found a three-byte solution which runs in three languages. – Peter Taylor Mar 23 '14 at 18:10
• J and K were designed as production languages, but I haven't seen anyone use them as such. What do they count in this chalenge? – John Dvorak Mar 24 '14 at 16:16
• "it will be counted as esoteric if no commercial company with at least 50 employees can be pointed to developing it's main product in the discussed language." - first off, I don't think this kind of data is readily available. Second, I doubt you'll find a company that still codes in Algol, Perl or Fortran. – John Dvorak Apr 4 '14 at 7:46

# Split string of powers of 2

I had this idea while playing 2048; Every single power of 2 is unique, even if it contains another power of 2 as a substring because there are none that consist entirely of powers of 2.

For example, the string "2048409632864" can be split into 2048, 4096, 32, 8, 64 easily enough, but it can also be split into 2, 0, 4, 8, 4, 0963, 2, 8, 6, 4 with a simple left-to-right algorithm, which is incorrect.

So, the challenge is to correctly split these numbers in the shortest byte count possible. Is this a good idea?

• But 128 can be split into 1 (20), 2 (21) and 8 (2**3) ... – r3mainer Mar 24 '14 at 15:13
• Related - and read the comments, because I think a lot of that discussion is relevant to this question. – Peter Taylor Mar 24 '14 at 15:53
• Does the program need to split the string into the smallest range possible? So if you get 2048, do you need go back and convert it into 2, 0, 4, 8? – user10766 Mar 24 '14 at 15:53
• also, that no word in a language can be decomposed does not imply that concatenations of words in that language are always unique. – John Dvorak Mar 24 '14 at 16:13

# A "counting" quine

and maybe . Hopefully codegolf.SE isn't tired of quines and quine-derivatives.

The aim of this golf is simple. Write a family of programs A and a single program B in your language, such that:

• Program A(N) produces the source code of A(N+1) when run, independent of file name, current date, contents of STDIN, or similar external variables.

• Program B, when given the source of A(N) as input, returns N. Input can be via STDIN, function argument, preinitialized single-character string variable, or language's equivalent.

Your score is the sum of the lengths of A(0) and B in bytes. Lowest score wins.

I called it a counting quine, because it is easiest to implement like a quine, except it also counts. The purpose of program B is to potentially allow for non-numeric changes between the programs in A, such as an increasing line of asterisks or something.

### Things to consider

Is this too similar to "Program that creates larger versions of itself (quine-variant)?"

Golfscript has a particularly powerful answer to the above question, that could be adapted to this challenge. It seems like it would beat even my best J, which itself is a curt 29 + 10 = 39 bytes. If this question is dissimilar enough to post, are we just going to bite the pillow and let these two duke it out? Is there some kind of restriction that might make this a little harder or more unique?

Alternatively, should this be a ? Maybe it would be more fun or interesting not to constrain cleverness by size requirements.

• Seems potentially even more suited for functional tarpits. I suspect zot might be a contender. But it's certainly the case that the better answers to the other question are trivially adapted, so it would seem to be a duplicate as written. One way of adapting it which might solve that problem is to require B = A(0), or even to generalise that a bit so that A(N) with no input / empty input outputs A(N+1) and with input of A(M) outputs M+N in decimal. – Peter Taylor Mar 28 '14 at 15:11
• You should give more importance to max(N) rather than code size. – user80551 Apr 3 '14 at 4:58
• @user80551 What for? That's not really an issue, even for the Golfscript solution, if you assume that time and space are not issues: theoretically N can reach to infinity. The same can be said of my J solution. However, it raises an interesting question: maybe this could be a [code-challenge], affected by the rate at which the program grows? Or maybe we take the max N, if all the programs in A have to be less than a certain filesize? Hmm... – algorithmshark Apr 3 '14 at 5:17

(this isn't quite a duplicate of Water-Bucket problem because that question was ill-posed and apparently abandoned; it's also not a duplicate of 3 and 5 Litre Jug Puzzle because that one was just a single instance, and an instance of a different problem to boot)

# die-harder

THE PROBLEM

In commemoration of Leslie Lamport's Turing Award, let's borrow a problem from his TLA+ online hyperbook. There are two versions: "Die Hard" and "Die Harder." "Die Hard" is an instance of the general, "Die Harder" problem. "Die Hard" is the following:

Given an empty jug, jug[0], with capacity 3 gallons; and an empty jug, jug[1], with capacity 5 gallons, deliver exactly 4 gallons of water under the following rules; you may:

1. fill a jug completely, making its current amount equal to its capacity
2. spill a jug completely, making its current amount equal to zero
3. pour into a jug from another, either filling the destination, emptying the source, or both

One solution is to

1. fill jug 1 (amounts are 0, 5)
2. pour jug 1 into jug 0 (amounts are 3, 2)
3. spill jug 0 (amounts are 0, 2)
4. pour jug 1 into jug 0 (amounts are 2, 0)
5. fill jug 1 (amounts are 3, 4)
6. spill jug 0 (amounts are 0, 4)

I believe there are 3 more.

"Die Harder" is the following:

Given an ordered collection of n empty jugs with non-zero, not-necessarily unique capacities c[0], c[1], ..., c[n-1], deliver exactly k gallons of water, which may be spread out over multiple jugs, under the same rules as above.

THE CHALLENGE

Beat my reference Clojure code code for

A: performance, by choice of algorithm or by optimization or both (my algorithm becomes intolerably slow when the number of jugs > 3)

B: clarity (no obfuscators; we want to see your algorithm)

C: elegance

D: brevity

The above expresses the priority of the judging criteria: perf is more important that clarity, which is more important than elegance, which is more important than brevity.

Your code should behave as follows:

Given n, capacities in the form of a bracketed list like [3 5 7] and a target amount k, print t solutions in a form like the following in Clojure syntax, which is a solution for n = 2, capacities = [3 5], k = 4, and t = 2:

({:states
[{:amount 0, :capacity 3, :id 0} {:amount 4, :capacity 5, :id 1}],
:trace
[(fill-jug 0)        (fill-jug 1)       (spill-jug 0)
(pour-from 0 1)     (spill-jug 0)      (pour-from 0 1)
(fill-jug 1)        (pour-from 0 1)    (spill-jug 0) ] }
{:states
[{:amount 3, :capacity 3, :id 0} {:amount 1, :capacity 5, :id 1}],
:trace
[(fill-jug 0)       (pour-from 1 0)     (fill-jug 0)
(pour-from 1 0)    (spill-jug 1)       (pour-from 1 0)
(fill-jug 0) ] } )


Each of your t solutions must present the final states of the jugs and a sequence of moves, in order, that achieve the solution. Minor variations to the above format are ok.

Extra credit if your code produces optimal (shortest number of moves, fewest pours, etc.) solutions and you can prove so. You may present proofs in commentary with your code; acceptance of a proof is at our sole discretion, as is judgment of clarity and elegance.

Include instructions for running your code if it's non-obvious (as in, "how exactly do I run this bit of INTERCAL?").

OBSERVATIONS

If the gcd of the capacities does not divide the target amount, the problem has no solution. In your golf, you might check this (my reference code assumes it, instead).

Certain moves, while legal, are trivial, namely:

1. filling a full jug
2. spilling an empty jug
3. pouring from an empty jug
4. pouring into a full jug
5. repeating the last move, whatever it was

In your golf, you may either check for these trivial moves or not.

You might unit-test your code on inputs like the following:

capacities = [3 5 7],    k = any integer from 0 through 15
capacities = [3 5 7 11], k = any integer from 0 through 26


A REFERENCE SOLUTION

You can find a reference solution in Clojure here. It includes unit tests that demonstrate the program at work.

• What's the scoring system? What's the licence supposed to cover? How much flexibility is supposed to be implied by "in a form like the following in Clojure syntax"? – Peter Taylor Apr 30 '14 at 8:40
• Great questions. Will revise. – Reb.Cabin Apr 30 '14 at 12:47
• In your example Die Hard solution, I'm thinking you made a mistake in step 5 - wouldn't the amounts become 2, 5? – golfer9338 May 17 '14 at 12:06
• I've got two solutions for Die Hard showing -- in the first one, after the fifth step, namely (spill-jug 0), the 3-jug (jug 0) has 0 and the 5-jug (jug 1) has 2. In the second solution, after the fifth step, namely (spill-jug 1), the 3-jug (jug 0) has 1 and the 5-jug (jug 1) has 0. Not sure where you're seeing my error :) – Reb.Cabin May 18 '14 at 13:25

I have not put substantial effort into this sandbox post. Since I am unsure(and it's probably not) whether this kind of question is a good fit for this site or not. If somebody reputable mentions that the idea has merit, I'll tune this sandbox up, and try to get it in shape for posting.

Obviously the biggest problem is how do you test the code? And that's the part I'm stuck on. If anyone can think of a way to overcome this please let me know! Anyway, here it is:

Write a program that posts itself as an answer

Your program must establish an http connection to codegolf.stackexchange.com, login, and post an answer to this question.

The answer must be in the form of:

"

## [Language]

Code


"

Rules: Cannot read source file, or any resource which is identical to your source file in any way.

Tags: popularity contest, quine

• Imagine what would happen if people try to test each answer! – Peter Taylor May 6 '14 at 22:04