What is Code Golf?
Code-golf is a competition to solve a particular problem in the fewest bytes of source code.
What are the requirements of Code Golf?
There should be a complete, unambiguous specification of the problem. It must include at least:
- How should the answer be presented – should a bare function be acceptable, or it must include full input/output code?
- The input format.
- The output format.
- A clear description of how the input and output are related.
- Explicit statement of any error checking or recovery that should be performed (because fragile solutions are, well, par for the course)
- Example inputs and outputs.
You, the asker, should be able to answer the code-golf problem – even if it's not optimal – to show that it is not a homework problem. If possible, post your solution as an answer.
All popular programming languages should be allowed. (Counter example)
What makes a good code-golf?
- Thoroughly specified.
- Simple enough to be understood fully in two quick readings of the spec.
- Admit rapid naive implementations.
- Complex enough to admit more than one reasonable way to accomplish it.
- Have built-in-to-some-languages solutions excluded (i.e. no
evalfor arithmetic parsers and the like).
- Not be optimized for one language or one class of languages.
- Not be too closely related to others we've done recently.
- Solve a class of problems rather than a single instance.
How should I answer a code-golf? Any hints?
Pick your favorite language, solve the problem, and squeeze the size as much as you can! Most of the time you'll need to use discouraged idioms. The standard approaches are:
- Remove unnecessary spaces and new lines.
- Use one-letter variables instead of descriptive names.
- Always remember that a boolean can be implicitly converted to a 0 or 1 in many languages, and you can perform arithmetic on a
charin C and C++.
- Study the language and the built-in libraries thoroughly. There are often “hidden” features that can solve the problem in much less bytes.
- Many times, a more inefficient algorithm can reduce the code size. (Example)
Things to note
Don't invent a domain-specific language just for solving this particular code golf, as in:
In MyFactorialGolfLang, the 1-byte program
Hreads a number and prints its factorial to stdout.
It's been done, trust us, and the joke is old hat.
- Avoid undefined, unspecified or implementation-defined behavior.
- If you use Unicode, byte count should use UTF-8.
- Try to explain your solution.
- You should show how the program or function is executed, accepting the input, and printing the output.