FizzBuzz/AWK: Difference between revisions
m
Fixed syntax highlighting.
(→Custom FizzBuzz: Example 2) |
m (Fixed syntax highlighting.) |
||
(One intermediate revision by one other user not shown) | |||
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.
<
#
BEGIN {
Line 24:
print "\n# Done."
}</
{{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.
<
BEGIN {RS=" "}
$1 % 15 == 0 {print "FizzBuzz"; next}
Line 52:
$1 % 3 == 0 {printf "Fizz "; next}
{printf "%3d ",$1}
'</
===One-liner with seq===
Like version 2, using bash with seq to generate the numbers as input. <br>
Line 60:
(Also, hard to read)
<
===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:
<
#
# FizzBuzz using no division & no modulo-operations:
Line 83:
}
print "\n# Done."
}</
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.
<
#
function prt(x,v) {
Line 113:
}
print "\n# Done."
}</
Same output as version 1.
===Custom FizzBuzz===
===Example program 1===
generated from [[General_FizzBuzz#AWK]],
Line 130:
<!-- http://ideone.com/yw1oEK -->
<
#
BEGIN {print "# CustomFizzBuzz:"}
Line 141:
{print " ",x; x=""}
END {print "# Done."} </
{{out}}
Line 179:
===Example program 2===
;Input: for the generator-program at [[General_FizzBuzz#AWK]]:
<pre>105
3 Fizz
5 Buzz
7 Baxx</pre>
▲<lang AWK>BEGIN {print "# CustomFizzBuzz:"}
$1 % 3 == 0 {x = x "Fizz"}
$1 % 5 == 0 {x = x "Buzz"}
$1 % 7 == 0 {x = x "Baxx"}
!x {print $1; next}
{print " ", x; x=""}
END {print "# Done."}</
|