FizzBuzz/AWK: Difference between revisions

-Version #
(-Version #)
Line 1:
{{collection|FizzBuzz}}
 
==Version 1 - regular if / else==
<!-- http://ideone.com/UrHdvd -->
This is the "traditional" approach:
Line 37:
# Done.
</pre>
When the output is presented like that, it is easy to see a pattern.
 
==Version 2 - bash with echo==
<!-- http://ideone.com/0VMIuO -->
Using echo from the shell to generate the numbers as input, .
 
soAdvantage: we need no loop inside the script.
 
Disadvantage: this needs a shell where echo can do this.
Line 52 ⟶ 54:
'</lang>
 
==Version 3 - oneOne-liner with seq==
 
AsLike version 2, using bash with seq to generate the numbers as input. <br>
Disadvantage: needs external command seq, i.e. this only works on unix.
(Also, hard to read)
 
<lang AWK>seq 100 | awk '$0=NR%15?NR%5?NR%3?$0:"Fizz":"Buzz":"FizzBuzz"'</lang>
 
==No divisions, using counters==
==Version 4 - no divisions==
<!-- http://ideone.com/uHmYUr -->
Division is one of the more expensive operations,
All processing is done inside awk,
so it is nice if we can avoid it.
using no division & no modulo, and instead some counters:
 
All processing is done inside awk, using no division & no modulo. <br>
Instead, a simple counter for each of the output-variants is used:
<lang AWK># usage: awk -v n=38 -f fizzbuzzNoDiv.awk
#
Line 80 ⟶ 86:
Same output as version 1.
 
==Version 5 - noNo divisions, repeatingusing pattern-string==
<!-- http://ideone.com/HJsrvl -->
Another solution that works without division / modulo. <br>
 
This is inspired by the versions "Without Modulus" of Nimrod and Python, <br>
using a precomputed/observed pattern to decide how to print each number. <br>
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
Anonymous user