FizzBuzz/AWK: Difference between revisions
Content added Content deleted
m (→Version 1 - regular if / else: printf) |
m (→Version 5 - no divisions, repeating pattern: more comments) |
||
Line 82: | Line 82: | ||
==Version 5 - no divisions, repeating pattern== |
==Version 5 - no divisions, repeating pattern== |
||
<!-- http://ideone.com/HJsrvl --> |
<!-- http://ideone.com/HJsrvl --> |
||
Another solution |
Another solution that works without division / modulo. <br> |
||
This is inspired by the |
This is inspired by the versions "Without Modulus" of Nimrod and Python, <br> |
||
using a precomputed pattern to decide |
using a precomputed/observed pattern to decide how to print each number. |
||
But here, the pattern is represented as chars in a string, instead of bits in an integer. |
|||
<lang AWK># usage: awk -v n=42 -f fizzbuzzRepeatPattern.awk |
<lang AWK># usage: awk -v n=42 -f fizzbuzzRepeatPattern.awk |
||
# |
# |
||
function prt(n,v) { |
|||
if( |
if(v==0) {printf("%3d ",n); return} # print number |
||
printf fb[ |
printf fb[v] # print text |
||
} |
} |
||
BEGIN { |
BEGIN { |
||
Line 96: | Line 96: | ||
print "# FizzBuzz:" |
print "# FizzBuzz:" |
||
pattern="003053003503006" # 0: print number, 3: print Fizz, etc. |
|||
split("1,2, Fizz,4, Buzz, FizzBuzz\n,", fb, ",") |
split("1,2, Fizz,4, Buzz, FizzBuzz\n,", fb, ",") |
||
while (i<n) { |
while (i<n) { |
||
i++; |
i++; sel++; |
||
prt(i, substr(pattern,sel,1) ); # select current variant from pattern |
|||
if( |
if(sel>length(pattern)) { sel=1; } |
||
} |
} |
||
print "\n# Done." |
print "\n# Done." |