Reputation: 1460
I am solving this question http://www.spoj.com/problems/NEXTODD/
In this question You have to solve it in minimum number of bytes.
My code :- {print$1%2?$1+2:$1+1}
which is 21 bytes.
Best solution is in 10 bytes.
Is there any other way to print $0 without using print or printf statement which can help me to reduce my code.
Upvotes: 2
Views: 174
Reputation: 1460
I also researched a trick for this.. can this be golfed ?
{$0=or($0+1,1)}1
Upvotes: 0
Reputation: 203712
All you need is the condition since it can never be non-zero and so will always invoke the default action of printing the current record:
awk '$0+=$0%2+1'
Upvotes: 2
Reputation: 198
In the pattern/action language of AWK, there is an implicit action of printing of $0 when the pattern evaluates to true, but there is no explicit action described. Regarding your challenge, see this example (13 characters):
{$0+=$0%2+1}1
Hat tip to 'some guy', who was quicker on the draw to post the code than me.
Upvotes: 4
Reputation: 5685
Shorter by two characters:
'{$0%2?$0+=2:$0+=1}1'
1
here instead of {print $0}
. 1
is pattern, that matches any record. {print $0}
is default action.
Edited. Even better ( -6 characters ):
{$0+=$0%2?2:1}1
Upvotes: 3