FizzBuzz/AWK: Difference between revisions

m
Fixed syntax highlighting.
m (→‎Example program 2: link to General_FizzBuzz#AWK)
m (Fixed syntax highlighting.)
 
Line 1:
{{collection|FizzBuzz}}
 
===regular if / else===
<!-- http://ideone.com/UrHdvd -->
This is the "traditional" approach:
Line 7:
Minor tweak: printf with no newline, and linebreaks only after each "FizzBuzz",
to get a more compact output.
<langsyntaxhighlight AWKlang="awk"># usage: awk -v n=38 -f FizzBuzz.awk
#
BEGIN {
Line 24:
 
print "\n# Done."
}</langsyntaxhighlight>
{{out}}
<pre>
Line 39:
When the output is presented like that, it is easy to see a pattern.
 
===bash with echo===
<!-- http://ideone.com/0VMIuO -->
Using echo from the shell to generate the numbers as input.
Line 46:
 
Disadvantage: this needs a shell where echo can do this.
<langsyntaxhighlight AWKlang="awk">echo {1..100} | awk '
BEGIN {RS=" "}
$1 % 15 == 0 {print "FizzBuzz"; next}
Line 52:
$1 % 3 == 0 {printf "Fizz "; next}
{printf "%3d ",$1}
'</langsyntaxhighlight>
 
===One-liner with seq===
 
Like version 2, using bash with seq to generate the numbers as input. <br>
Line 60:
(Also, hard to read)
 
<langsyntaxhighlight AWKlang="awk">seq 100 | awk '$0=NR%15?NR%5?NR%3?$0:"Fizz":"Buzz":"FizzBuzz"'</langsyntaxhighlight>
 
===No divisions, using counters===
<!-- http://ideone.com/uHmYUr -->
Division is one of the more expensive operations,
Line 69:
All processing is done inside awk, using no division & no modulo. <br>
Instead, a simple counter for each of the output-variants is used:
<langsyntaxhighlight AWKlang="awk"># usage: awk -v n=38 -f fizzbuzzNoDiv.awk
#
# FizzBuzz using no division & no modulo-operations:
Line 83:
}
print "\n# Done."
}</langsyntaxhighlight>
Same output as version 1.
 
===No divisions, using pattern-string===
<!-- http://ideone.com/HJsrvl -->
Another solution that works without division / modulo.
Line 94:
But here, the pattern is represented as chars in a string,
instead of bits in an integer.
<langsyntaxhighlight AWKlang="awk"># usage: awk -v n=42 -f fizzbuzzRepeatPattern.awk
#
function prt(x,v) {
Line 113:
}
print "\n# Done."
}</langsyntaxhighlight>
Same output as version 1.
 
===Custom FizzBuzz===
===Example program 1===
generated from [[General_FizzBuzz#AWK]],
Line 130:
 
<!-- http://ideone.com/yw1oEK -->
<langsyntaxhighlight AWKlang="awk"># usage: awk -f fizzbuzzCustom.awk numbers.txt
#
BEGIN {print "# CustomFizzBuzz:"}
Line 141:
{print " ",x; x=""}
 
END {print "# Done."} </langsyntaxhighlight>
 
{{out}}
Line 185:
7 Baxx</pre>
 
<langsyntaxhighlight AWKlang="awk">BEGIN {print "# CustomFizzBuzz:"}
 
$1 % 3 == 0 {x = x "Fizz"}
Line 194:
{print " ", x; x=""}
END {print "# Done."}</langsyntaxhighlight>
9,476

edits