FizzBuzz/AWK: Difference between revisions

Remarks
(FizzBuzz / AWK)
 
(Remarks)
Line 1:
{{collection|FizzBuzz}}
 
===Version 1 - regular if / else===
with linebreaks after each "FizzBuzz": <!-- http://ideone.com/UrHdvd -->
This is the "traditional" approach:
Loop, and modulo-check to see what to print. <br>
Minor tweak: linebreaks after each "FizzBuzz",
to get a more compact output.
<lang AWK># usage: awk -v n=38 -f FizzBuzz.awk
#
Line 8 ⟶ 12:
if(!n) n=100
print "# FizzBuzz:"
 
for (ii=1; ii<=n; ii++)
if (ii % 15 == 0)
Line 17 ⟶ 22:
else
{printf "%3d ", ii}
 
print "\n# Done."
}</lang>
Line 32 ⟶ 38:
</pre>
 
===Version 2 - bash with echo===
using echo to generate the numbers: <!-- http://ideone.com/0VMIuO -->
Using echo to generate the numbers as input,
so we need no loop inside the script.
 
Disadvantage: this needs a shell where echo can do this.
<lang AWK>echo {1..100} | awk '
BEGIN {RS=" "}
Line 42 ⟶ 52:
'</lang>
 
===Version 3 - one-liner with seq===
 
As version 2, using bash with seq to generate the input:. <!-- http: --br>
Disadvantage: needs external command seq, i.e. only works on unix.
 
<lang AWK>seq 100 | awk '$0=NR%15?NR%5?NR%3?$0:"Fizz":"Buzz":"FizzBuzz"'</lang>
 
===Version 4 - no divisions===
awk, using no division & no modulo: <!-- http://ideone.com/uHmYUr -->
All processing is done inside awk,
using no division & no modulo, and instead some counters:
<lang AWK># usage: awk -v n=38 -f fizzbuzzNoDiv.awk
#
Line 57 ⟶ 72:
c1++; c3++; c5++; cF++; x=sprintf("%3d ",c1)
if(c3>= 3) { c3=0; x="Fizz " }
if(c5>= 5) { c5=0; x="Buzz " }
if(cF>=15) { cF=0; x="FizzBuzz\n" }
printf(x)
Line 65 ⟶ 80:
Same output as version 1.
 
===Version 5 - no divisions, repeating pattern===
another solution with no division & no modulo: <!-- http://ideone.com/jF9DddHJsrvl -->
Another solution with no division & no modulo.
This is inspired by the version "Without Modulus" of Nimrod,
using a precomputed pattern to decide what to print.
 
<lang AWK># usage: awk -v n=42 -f fizzbuzzRepeatPattern.awk
#
Anonymous user