Hot answers tagged

132

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


86

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)...


75

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

Merge Loops You can usually merge two consequent loops, or two nested loops, into one. Before: for (i=0; i<a; i++) foo(); for (i=0; i<b; i++) bar(); After: for (i=0; i<a+b; i++) i<a?foo():bar();


65

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 ...


63

Just to mention the obvious: Question your choice of algorithm and try something entirely new. When golfing (especially harder problems that result in longer programs) all too often you might stick to the path you first chosen without trying other fundamental options. Of course, you may micro-golf one or a few lines at a time or a part of the overall idea, ...


60

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! ...


59

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 ...


54

A nice way to convert an iterable to list on Python 3: imagine you have some iterable, like i = (1,2,3,4) i = range(4) i = (x**2 for x in range(5)) But you need a list: x=list(i) #the default way *x,=i #using starred assignment -> 4 char fewer It's very useful to make a list of chars out of a string s=['a','b','c','d','e'] s=list('abcde') *s,='...


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.


52

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!


49

Instead of range(x), you can use the * operator on a list of anything, if you don't actually need to use the value of i: for i in[1]*8:pass as opposed to for i in range(8):pass If you need to do this more than twice, you could assign any iterable to a variable, and multiply that variable by the range you want: r=1, for i in r*8:pass for i in r*1000:pass ...


49

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 ...


49

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()


47

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


45

Some tips: In R, it's recommended to use <- over =. For golfing, the opposite holds since = is shorter... If you call a function more than once, it is often beneficial to define a short alias for it: as.numeric(x)+as.numeric(y) a=as.numeric;a(x)+a(y) Partial matching can be your friend, especially when functions return lists which you only need ...


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 ...


44

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.


44

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 ...


40

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 ...


38

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 ...


37

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

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 ...


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;}


35

This one is lesser known and lesser used, but can be impressive if used in the right situation. Consider a function that takes no arguments and always returns a different number when called, and the returned number will be used in a calculation: var a = [ Math.random()*12|0, Math.random()*11|0, Math.random()*10|0, /* etc... */ ]; You ...


34

Initialize variables using values you already have. Instead of x=1, try to look for something that already equals 1. For example, a function's return value: printf("..");x=0; -> x=!printf("..");. It's easiest with 0, because you can always negate, or when all you need is the right truth value (and don't care if it's 1 or 19).


34

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).)"


33

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: ...


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