Skip to content

Instantly share code, notes, and snippets.

bfontaine/code_golf.awk

Last active December 8, 2021 08:46
Show Gist options
• Save bfontaine/ba93dfca189a01d2b5858e6c6574b400 to your computer and use it in GitHub Desktop.
Awk code-golf tips
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
 # save 1 char by using 'for' instead of 'while' x=42;while(c) for(x=42;c;) # save 1 char by using a missing variable instead of "" split(\$0,b,"") split(\$0,b,X) # use ternary operations when possible if(c)a else b c?a:b # if there's no else, use '0' or another no-op value if(c)a c?a:0 # assignments are expressions, so you can combine them if(c){a=1;b=2} c?a=(b=2)-1:0 n=a-b;n=n<0?-n:n n=(n=a-b)<0?-n:n \$1>p?n++:0;p=\$1 p<(p=\$1)?n++:0 n+=p<(p=\$1) # remove brackets as much as you can for(…){for(…){if(…){…}else{…}}} for(…)for(…)…?…:… # move ++/--/+=/etc inside expressions for(;d<80;d++) for(;d++<80;) # booleans are 1/0 if(a==0) if(!a) # split returns the length split(\$0,X,",");…;print length(\$0) l=split(\$0,X,",");…;print l # you don't need a semicolon after a closing bracket for(…){…};print x for(…){…}print x # move conditions outside the block {\$0>n?n*=2:0} \$0>n{n*=2}
to join this conversation on GitHub. Already have an account? Sign in to comment