FizzBuzz
Tom Scott has a great video about the FizzBuzz interview question used by Google and others. The programming problem is to print out numbers within a loop, except if the number is divisible by 3 then print "Fizz" and if it's divisible by 5 print "Buzz". And if it's divisible by both, print "FizzBuzz". Sounds easy, but it requires a little thought. |
|
Here's our solution in Forth:
: fizz ( n -- rem , divisible by 3? )
3 mod
dup 0= if
." Fizz"
then
;
: buzz ( n -- rem , divisible by 5? )
5 mod
dup 0= if
." Buzz"
then
;
: fizzbuzz ( n -- , fizzbuzz )
dup
for
cr
dup i -
dup fizz
over buzz
* if \ if neither remainders are 0, print number
. else drop
then
next
drop
;
To test it:
20 fizzbuzz
100 fizzbuzz
How long does it take to run on a Scamp?
ticks 100 fizzbuzz ticks - abs .
gives a result of 15 ms.
In comparison, Fizzbuzz solutions in python, running on a PC, have been benchmarked between 200 ms and 400 ms.
In comparison, Fizzbuzz solutions in python, running on a PC, have been benchmarked between 200 ms and 400 ms.