avinashse
avinashse

Reputation: 1460

Any Other way to print $0 without using print in awk?

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

Answers (4)

avinashse
avinashse

Reputation: 1460

I also researched a trick for this.. can this be golfed ?

{$0=or($0+1,1)}1

Upvotes: 0

Ed Morton
Ed Morton

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

taltman
taltman

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

Nikolai Popov
Nikolai Popov

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

Related Questions