Tips for golfing in Mathematica
Some built-in functions with long names can be replaced with shorter expressions.
For example:
Total
=>Tr
Transpose
=>Thread
or\[Transpose]
True
=>1<2
False
=>1>2
Times
=>1##&
Alternatives
=>$|##&
IntegerQ
=>⌊#⌋==#&
a[[1]]
=>#&@@a
a[[All,1]]
=>#&@@@a
ConstantArray[a,n]
=>Array[a&,n]
orTable[a,{n}]
Union@a
=>{}⋃a
ora⋃a
ToExpression@n
=>FromDigits@n
ifn
is a numberDivisible[n,m]
=>m∣n
FromDigits[n,2]
=>Fold[#+##&,n]
ifn
is a list of0
s and1
sComplex@z
=>{1,I}.z
wherez
is a list of the form{x,y}
Tips below vary from the most economical to the most often used:
Use Mathematica's high-level commands where possible, even bulky ones:
MorphologicalComponents
: Code-Golf: Count IslandsImage manipulation capabilities: e.g. Today (September 24) is HONDA birthday
Subsets
IntegerPartitions
Distance and Similarity measures: e.g.
EuclideanDistance
can be a byte saver. Note however, that it's usually shorter to writeTotal@Abs[a-b]
instead ofa~ManhattanDistance~b
andMax@Abs[a-b]
instead ofa~ChessboardDistance~b
.
Use
Graphics and
Text
for Ascii art: e.g Star programming! and Build an analog clockDedicated symbols:
logic and set operations symbols instead of their long form names: ⋂, ⋃, ∧, ∨
Map
andApply
:/@
,//@
.@@
,@@@
Prefix and infix notation:
Print@"hello"
in place ofPrint["hello"]
a~f~b
in place off[a,b]
When a function is used only once, a pure function may economize a character or two.
Joining strings in a list.
""<>{"a","b","c"}
instead ofStringJoin@{"a","b","c"}
Exploit listable functions. The longer the lists the better.
{a, b, c} + {x, y, z}= {a+x, b+y, c+z}
{2, 3, 4} {5, 6, 7}= {10, 18, 28}
{{a, b}, {c, d}}^{2, 3} = {{a^2, b^2}, {c^3, d^3}}
Lists with repeated values
This is quite a common vector to work with:
{0,0}
It turns out this can be shortened by a byte:
0{,}
Even more bytes are saved if the vector is longer than two zeros. This can also be used to initialise zero matrices, e.g. the following gives a 2x2 matrix of zeros:
0{{,},{,}}
This can also be used for non-zero values if they're sufficiently large or sufficiently many or negative. Compare the following pairs:
{100,100}
0{,}+100
{-1,-1}
0{,}-1
{3,3,3,3}
0{,,,}+3
But remember that starting at 6 values, you're better off with 1~Table~6
in this case (potentially earlier, depending on precedence requirements).
The reason this works is that ,
introduces two arguments to the list, but omitted arguments (anywhere in Mathematica) are implicit Null
s. Furthermore, multiplication is Listable
, and 0*x
is 0
for almost any x
(except for things like Infinity
and Indeterminate
), so here is what's happening:
0{,}
= 0*{,}
= 0*{Null,Null}
= {0*Null,0*Null}
= {0,0}
For lists of 1
s, you can use a similar trick by making use of exponentiation rules. There are two different ways to save bytes if you have at least three 1
s in the list:
{1,1,1}
1^{,,}
{,,}^0