# Tips for golfing in <all languages>

The aim of this post is to gather all the golfing tips that can be easily applied to <all languages> rather than a specific one.

Only post answers that its logic can be applied to the majority of the languages

• "Majority" by what metric? – ceased to turn counterclockwis Mar 27 '12 at 10:41
• @leftaroundabout by the metric of the same word – ajax333221 Mar 27 '12 at 22:01
• The problem is that many languages are (often short-lived) experimental ones with very untypical paradigms, for which typical programming expressions don't make any sense at all. So "majority of all languages" it virtually impossible to fulfill. You should restrict it in some way, e.g. to "majority of languages regularly used on codegolf.SE". At the moment, the answers look quite a lot like "the majority of remotely C-derived languages", but those, albeit the vast majority of all written code is written in them, are not the majority of languages. – ceased to turn counterclockwis Mar 27 '12 at 22:51
• leftroundabout, I guess we all know what they roughly mean. This is about mostly language-independent optimizations, i.e those not only useful in Brainfuck but maybe Python, C, Java and Fortran at once. General ideas that you can apply in many languages that work similarly. I don't think there is a need to be that precise and specific in tips and a CW question. This is about helping others to golf, not about pissing them off. – Joey Apr 5 '12 at 6:10
• Hopefully nobody creates a language called <all languages>... – mbomb007 Apr 4 '16 at 21:19

# Find better ways to initialise your variables

Some other answers came close to mentioning this already, but in many (strictly typed?) languages, it's shorter to initialise x as empty string like:

x:=""


or x as empty rune (char) like:

x:=''


than

var x string


and

var x rune


Using preexisting values is obviously preferred, but not so easy.

You spend your time looking to get rid of O(n^2) algorithms and bring runtime and memory use down; golf turns that around - spend freely of CPU and Memory to bring code size down. Use nested loops, calculate 10x too much data instead of a complex exit condition, call sort() every loop iteration instead of storing the result.

Some questions have a runtime limit to push you to write a more efficient answer, even then knowing how fast your language and code runs can give you room to take liberties and still stay within it.

# Use truth tables

An example condition can be (((A AND B) OR (A OR B)) AND C) OR (A OR C) with A, B and C being boolean variables. But it's so long! Is there any way to shorten it, and prove it acts the same after shortening? Well, truth tables to the rescue!

A B C D=A AND B E=A OR B F=D OR E G=F AND C H=A OR C I=G OR H
0 0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 1 1
0 1 0 0 1 1 0 0 0
0 1 1 0 1 1 1 1 1
1 0 0 0 1 1 0 1 1
1 0 1 0 1 1 1 1 1
1 1 0 1 1 1 0 1 1
1 1 1 1 1 1 1 1 1

The truth table above represents the possible values and outcomes of the example condition we specified earlier. D, E, F, G and H are variables which make our life a lot easier. You can see what they're assigned to at the top row of the table. The final variable, I, is the outcome of the condition. So, now that we have the outcomes handy, we can simplify the table to just the base variables and the final outcome:

A B C I
0 0 0 0
0 0 1 1
0 1 0 0
0 1 1 1
1 0 0 1
1 0 1 1
1 1 0 1
1 1 1 1

We can now relatively easily see that the condition above really reduces to just A OR C.

• One can also try and ask WolframAlpha. – Jonathan Frech Feb 23 '18 at 23:51
• @JonathanFrech But how are you going to prove it then? ;) – Erik the Outgolfer Feb 24 '18 at 0:30
• Outsource the proof and trust. – Jonathan Frech Feb 24 '18 at 1:01
• @JonathanFrech Sorry, but you must be able to prove your answers by yourself, and Wolfram|Alpha doesn't have a proof, so I'm afraid it isn't going to help you much. :) – Erik the Outgolfer Feb 24 '18 at 11:15
• Using a K-map would be more systematic and guarantees an optimal solution. – ბიმო Dec 27 '18 at 22:37

## Know the difference between "program" and "function" in your language

Many questions on codegolf.SE ask you to "write a program or function"; this gives you some freedom to play to the strengths of your language and runtime based on how it handles command line parameters, how much boilerplate it needs for defining functions and their parameters, for defining full programs, for reading user input in a running program.

e.g. for a question asking you to write a program or function which takes a number as input, multiplies it by 10 and prints the result:

in Python it might go this way:

print(10*int(input()))    # full program
lambda x:print(10*x)      # function


in APL, the other way:

⎕←10×⎕      # full program
{⎕←10×⍵}    # function


0|$f # -2 bytes parseInt(f) # Javascript (Never use Math.floor) 0|f  This will truncate downwards (for positive values), and to get the ceil instead, it can be achieved with the same trick by reflecting the value across 0 (not true in all languages / implementations, not always shorter): (i/5.0).ceil # Ruby -(i/-5)  ## eval() is perfectly safe In more dynamic languages it can help to make a string of code and then eval() it (or the equivalent in your language), as a way to repeat chunks of code by inserting the code into the right places as a string replace without the overhead of defining and calling functions, or to loop N times without loop boilerplate. e.g. in Python to print "hello" five times: for i in range(5):print("hello") exec('print("hello");'*5)  e.g. in PowerShell calling [math]::Truncate() three times becomes slightly shorter as a function, and slightly shorter again doing a string replace on code and then evaluating it: $a=[math]::Truncate($a/$b);$b=[math]::Truncate($c/$a);$c=[math]::Truncate($d/$e)

function T($a,$b){[math]::Truncate($a/$b)};$a=T$a $b;$b=T $c$a;$c=T$d $e '$a=T($a/$b);$b=T($c/$a);$c=T($d/$e)'|% r*ce T [math]::Truncate|iex


# Don't be afraid to put non-printables in your code.

Sometimes, instead of using escapes like \0, \x1f, \033, \n, or \u0003, you can just put the codepoint in the string verbatim. You may need to input code points manually using keyboard shortcuts, a hex editor, or a good old printf "\x1f" >> file

Note that you cannot copy and paste null bytes on Windows.

Since Stack Exchange doesn't play well with non-printables (and they are difficult to read), I like to represent them by <kbd> tags: (make sure to use language-all and escape < and > in the code block)

<!-- language-all: lang-c -->
<pre><code>char str[]="abc<kbd>00</kbd>def";</code></pre>

char str[]="abc00def";

This is very useful for making lookup tables in languages where strings can be indexed like arrays for their codepoint, such as C, C++, asm, C#, and Python (with b''), since the non-printables consist of the first 32 bytes.

int l[]={2,9,31,7};l[x]; // 23 bytes
"02091f07"[x]; // 10 bytes


This also can apply to invalid UTF-8 sequences, but that is very fragile in practice and far less useful.

## Use magic numbers / magic strings

Code golfers tend to forget using magic numbers while they're golfing, so I'm putting some ways to make magic numbers here.

• The easiest way a magic number can be used is if the list or string you need to encode is one of two values (and then you can use bit-shifts and logical and to access the bitwise values stored in the magic number).

• e.g. this answer is a pretty good usage of this type of magic numbers.
• You can also construct magic numbers/strings via brute force or a similar method.