HP Forums
Fizzbuzz, again - Printable Version

+- HP Forums (https://www.hpmuseum.org/forum)
+-- Forum: HP Calculators (and very old HP Computers) (/forum-3.html)
+--- Forum: General Forum (/forum-4.html)
+--- Thread: Fizzbuzz, again (/thread-9155.html)

Fizzbuzz, again - brickviking - 09-25-2017 09:45 AM

The last time I saw this in the forums was in a FOCAL discussion, but I first ran into it somewhere else. Those of you who know what FIZZBUZZ is, won't need this explanation, but for everyone else who's not in the loop, fizzbuzz is a children's number game.

Numbers are counted from 1 to ... however many. There's a twist. If the number's divisible by 3, you say "fizz". If the number's divisible by 5, you say "buzz" instead. If it's divisible by both 3 and 5, you say fizzbuzz. Everything else, you simply say the number. A sample run would go like this:
1, 2, fizz, 4, buzz, fizz, 7, 8, fizz, buzz, 11, fizz, 13, 14, fizzbuzz, 16, 17, fizz, ... etc.

Here's my rough-cut example, I've had a rat-through and removed most of the bugs I know about. Could you suggest improvements?

progname: FBTST
@ This takes one arg on stack and reports arg, fizz or buzz
@ fizz if divisible by 3, buzz if divisible by 5 and "fizzbuzz" if both
@ replies the arg otherwise
  'J' STO
  "" 'K' STO
  'J' RCL
  DUP @ copy for if-test
    3. MOD NOT 
    'K' "FIZZ" STO+
  @ This tests the first J value
    5. MOD NOT
   'K' "BUZZ" STO+
@ grab this back out for a quick test
  'K' RCL
    SIZE 1 < @ Is it empty?
    'J' RCL  @ spit the value back out
    'K' RCL @ otherwise, spit out fizz,buzz or fizzbuzz

To get the complete sequence of numbers (at least to whatever I specify on the stack), I use the following dead simple loop.

Progname: FBLP
@ Accepts two args on stack. 2: 1  1:25  loops from 1 to 25
@ alternative would have been 1. 25. FOR J J FBTST NEXT

My ideal would be to not need two spare vars and to operate using just the stack, but I then have to start learning how to use ROLL, PICK, or ROT in various incarnations. I don't know whether that will make the program larger, but I'll give that a go within the next few days.

(Post 97)

RE: Fizzbuzz, again - Dave Britten - 09-25-2017 08:08 PM

Under normal circumstances, you don't have to RCL variable values. Just do K rather than 'K' RCL, for example.

Here's a little quick-and-dirty version I banged out on my 48SX that demonstrates using a local subroutine, and doing more "on the stack".

  DUP2 SWAP - 1 +
  \<< DUP 3 MOD NOT "FIZZ" "" IFTE
  \-> N FB
  \<< FOR C C FB EVAL NEXT N \->LIST \>>