Anonymous user
FizzBuzz/AWK: Difference between revisions
Remarks
(FizzBuzz / AWK) |
(Remarks) |
||
Line 1:
{{collection|FizzBuzz}}
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>
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>
As version 2, using bash with seq to generate the input
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>
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(cF>=15) { cF=0; x="FizzBuzz\n" }
printf(x)
Line 65 ⟶ 80:
Same output as version 1.
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
#
|