FizzBuzz/AWK: Difference between revisions

Content added Content deleted
Line 82: Line 82:
==Version 5 - no divisions, repeating pattern==
==Version 5 - no divisions, repeating pattern==
<!-- http://ideone.com/HJsrvl -->
<!-- http://ideone.com/HJsrvl -->
Another solution with no division & no modulo.
Another solution that works without division / modulo. <br>
This is inspired by the version "Without Modulus" of Nimrod,
This is inspired by the versions "Without Modulus" of Nimrod and Python, <br>
using a precomputed pattern to decide what to print.
using a precomputed/observed pattern to decide how to print each number.
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
<lang AWK># usage: awk -v n=42 -f fizzbuzzRepeatPattern.awk
#
#
func p(n,t) {
function prt(n,v) {
if(0+t==0) {printf("%3d ",n); return}
if(v==0) {printf("%3d ",n); return} # print number
printf fb[t]
printf fb[v] # print text
}
}
BEGIN {
BEGIN {
Line 96: Line 96:
print "# FizzBuzz:"
print "# FizzBuzz:"


F="003053003503006"
pattern="003053003503006" # 0: print number, 3: print Fizz, etc.
split("1,2, Fizz,4, Buzz, FizzBuzz\n,", fb, ",")
split("1,2, Fizz,4, Buzz, FizzBuzz\n,", fb, ",")


while (i<n) {
while (i<n) {
i++; fmt++;
i++; sel++;
p(i, substr(F,fmt,1) )
prt(i, substr(pattern,sel,1) ); # select current variant from pattern
if(fmt>length(F)) { fmt=1; }
if(sel>length(pattern)) { sel=1; }
}
}
print "\n# Done."
print "\n# Done."