Hot answers tagged

134

Splitting with numbers to save the quotemarks: "alpha,bravo,charlie".split(",") // before "alpha0bravo0charlie".split(0) // after


87

Use the most recent possible java. Java 8 lets you use lambda expressions, so use it if you need anything even like functional objects. Define shortened functions for things you use a lot. For instance, you have a hundred calls to exampleClassInstance.doSomething(someParameter), define a new function void d(ParameterType p){exampleClassInstance.doSomething(p)...


82

Store lookup tables as magic numbers Say you want to hardcode a Boolean lookup table, like which of the first twelve English numbers contain an n. 0: False 1: True 2: False 3: False 4: False 5: False 6: False 7: True 8: False 9: True 10:True 11:True 12:False Then, you can implement this lookup table concisely as: 3714>>i&1 with the resulting 0 ...


72

Collapse two numerical loops into one Say you're iterating over the cells of an m*n grid. Instead of two nested for loops, one for the row and one of the columns, it's usually shorter to use a single loop to iterate over the m*n cells of the grid. You can extract the row and column of the cell inside the loop. Original code: for i in range(m): for j in ...


66

For integer n, you can write n+1 as -~n n-1 as ~-n because the bit flip ~x equals -1-x. This uses the same number of characters, but can indirectly cut spaces or parens for operator precedence. Compare: while n-1: #Same as while n!=1 while~-n: c/(n-1) c/~-n or f(n)+1 or-~f(n) (n-1)/10+(n-1)%10 ~-n/10+~-n%10 The operators ~ and unary - are ...


65

Avoid catastrophic function-argument type declarations If you're declaring a function where all five arguments are ints, then life is good. you can simply write f(a,b,c,d,e){ But suppose d needs to be a char, or even an int*. Then you're screwed! If one parameter is preceded by a type, all of them must be: f(int a,int b,int c,int*d,int e){ But wait! There ...


57

This isn't the same solution as llhuii's, but it's also 42 bytes long. n=0;exec'print n;n^=(n^n+2)%3/2;n+=2;'*400 Try it online! Thanks to @JonathanFrech, we're now at 40 bytes. n=0;exec'print n;n=n+2^(n^n+2)/2%3;'*400 Try it online! There's another byte to be saved, for a total of 39. n=0;exec'print n;n=n+2^-(n^n+2)%3;'*400 Try it online!


54

You can use the good old alien smiley face to reverse sequences: [1, 2, 3, 4][::-1] # => [4, 3, 2, 1]


53

Shorter random number generation If you need a random boolean (0 or 1): new Date&1 // equivalent to Math.random()<0.5 If you need a random integer 0 <= n < 1337: new Date%1337 // equivalent to Math.floor(Math.random()*1337)) This works because a Date is stored internally in JavaScript as the amount of milliseconds since an epoch, so the new ...


52

Use Test-Driven Development If the code must handle various inputs, then write comprehensive tests and make it easy to run them all very quickly. This allows you to try risky transforms one baby step at a time. Golfing then becomes like refactoring with perverse intent.


50

Try to reduce logical statements For example, if A and B are booleans and your language treats booleans like numbers to some extent, A and (not B) and A>B are equivalent. For example in Python if A and not B: foo() is the same as: if A>B: foo()


49

Extended iterable unpacking ("Starred assignment", Python 3 only) The best way to explain this is via an example: >>> a,*b,c=range(5) >>> a 0 >>> b [1, 2, 3] >>> c 4 We've already seen a use for this — turning an iterable into a list in Python 3: a=list(range(10)) *a,=range(10) Here are a few more uses. Getting the ...


47

Spread operator ... The spread operator transforms an array value into a comma separated list. Use case 1: Directly use an array where a function expects a list list=[1,2,3] x=Math.min(...list) list=[10,20], a.push(...list) // similar to concat() Use case 2: Create an array literal from an iterable (typically a string) [...'buzzfizz'] // -> same as ...


46

Use interface instead of class. In java 8, static methods were added to interfaces. In interfaces, all methods are public by default. Consequently class A{public static void main(String[]a){}} can now be shortened to interface A{static void main(String[]a){}} which is obviously shorter. For example, I used this feature in the Hello, World! challenge.


45

Define infix operators instead of binary functions This saves usually one or two spaces per definition or call. 0!(y:_)=y x!(y:z)=(x-1)!z vs. f 0(y:_)=y f x(y:z)=f(x-1)z The available symbols for 1-byte operators are !, #, %, &, and ?. All other ASCII punctuation is either already defined as an operator by the Prelude (such as $) or has a special ...


40

For ages it bothered me that I couldn't think of a short way to get the entire alphabet. If you use range enough that R=range is worth having in your program, then [chr(i+97)for i in R(26)] is shorter than the naive 'abcdefghijklmnopqrstuvwxyz' , but otherwise it's longer by a single character. It haunted me that the clever one that required some ...


39

Instead of >= and <= you can simply use integer division (/) when the compared values are above zero, which saves one character. For example: putchar(c/32&&126/c?c:46); //Prints the character, but if it is unprintable print "." Which is of course still shrinkable, using for example just > and ^ (a smart way to avoid writing && or || in ...


38

With varargs you can "cast" a parameter to an array of the same type: void f(String...x){ x=x[0].split("someregex"); // some code using the array } instead of void f(String s){ String[]x=s.split("someregex"); // some code using the array }


37

Python 2 - 12 characters print 8**999 The decimal representation of all even numbers from 0 to 100 can be found in the output: ...


36

Use unary ~ for x+1 and x-1 This trick applies to languages that have a unary bitwise negation operator ~ and a unary regular negation operator -. If your program, by chance, contains the expression -x-1, you can replace it with ~x to save bytes. This doesn't occur all too often, but watch what happens if we negate (-) both expressions: x+1 equals -~x! ...


36

Undocumented, but works in every version I've run into for legacy sh backwards compatibility: for loops allow you to use { } instead of do done. E.g. replace: for i in {1..10};do echo $i; done with: for i in {1..10};{ echo $i;}


36

Getting 39 bytes This is an explanation of how I got a 39-byte solution, which Dennis and JonathanFrech found separately as well. Or, rather, it explains how one could arrive at the answer in hindsight, in a way that's much nicer than my actual path to it, which was full of muddy reasoning and dead ends. n=0 exec"print n;n=n+2^-(n+2^n)%3;"*400 Writing ...


35

Although python doesn't have switch statements, you can emulate them with dictionaries. For example, if you wanted a switch like this: switch (a): case 1: runThisCode() break case 2: runThisOtherCode() break case 3: runThisOtherOtherCode() break You could use if statements, or you could use this: ...


35

Python 3 does not have cmp. For golfing, you can do 11 chars (a>b)-(a<b) which loses 3 chars over cmp(a,b). Amusingly, this is also an "official" workaround. The What's New in Python 3 page says "(If you really need the cmp() functionality, you could use the expression (a > b) - (a < b) as the equivalent for cmp(a, b).)"


34

When you have two boolean values, a and b, if you want to find out if both a and b are true, use * instead of and: if a and b: #7 chars vs if a*b: #3 chars if either value is false, it will evaluate as 0 in that statement, and an integer value is only true if it is nonzero.


32

With a static import: import static java.lang.System.out; // even shorter (thanks to Johannes Kuhn): import static java.lang.System.*; you can save some boilerplate later, but you need multiple invocations to reach a payoff: public static void main (String[] args) { out.println ("foo"); out.println ("bar"); out.println ("baz"); }


32

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] or Table[a,{n}] Union@a => {}⋃a ...


31

Use ~ to index from the back of a list If L is a list, use L[~i] to get the i'th element from the back. This is the i'th element of the reverse of L. The bit complement ~i equals -i-1, and so fixes the off-by-one error from L[-i].


31

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 Islands Image manipulation capabilities: e.g. Today (September 24) is HONDA birthday Subsets IntegerPartitions Distance and Similarity measures: e.g. EuclideanDistance can be a ...


31

Python 3, 22 (Possibly not allowed) If the challenge is "to create a python script which prints the even numbers from 0 to 100" and not "to create a python script which prints the even numbers from 0 to 100, newline separated", then the shortest solution is: print(*range(0,101,2)) Remember, it's very important in code golf not to put any ...


Only top voted, non community-wiki answers of a minimum length are eligible