Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- So, I ran across the "FizzBuzz" interview question in a geek article at Los Techies:
- http://lostechies.com/jimmybogard/2013/01/29/fizzbuzz-is-dead-long-live-fizzbuzz
- By the time I got tired of obsessing over it, I had eight distinct JavaScript solutions (see http://pastebin.com/bsKvNzMD ). Of course, this was all hacked out in the comfort of my favorite overstuffed armchair at home. Here's my pick of the litter.
- function FizzBuzz(fizz, buzz, fizzNum, buzzNum, last) {
- var msgs = [0, fizz, buzz, fizz + buzz];
- var rpt = new Array();
- for (var i = 1; i <= last; i++) {
- msgs[0] = "" + i;
- rpt.push(msgs[((0 == i%fizzNum)?1:0) + ((0 == i%buzzNum)?2:0)]);
- }
- return rpt;
- };
- The "standard answer" is given by the call:
- FizzBuzz("Fizz", "Buzz", 3, 5, 100)
- The expression
- ((0 == i%fizzNum)?1:0) + ((0 == i%buzzNum)?2:0)
- implements the following partition of the decision universe and the corresponding numerical results:
- Fizz Buzz
- i divisible i divisible
- by fizzNum by buzzNum Fizz + Buzz
- ----------- ----------- ------------------------
- F => 0 F => 0 0 + 0 = 0 => "" + i
- T => 1 F => 0 1 + 0 = 1 => fizz
- F => 0 T => 2 0 + 2 = 2 => buzz
- T => 1 T => 2 1 + 2 = 3 => fizz + buzz
- Prob'ly not the answer I'd have produced during a job interview, since this version is a refinement of the fifth solution generated during my geek sprint.
- Ah, OCD! Okay, one more generalization of the FizzBuzz notion...
- function Fuzz(fuzzes, fuzzNums, last) {
- var msg;
- var rpt = new Array();
- var lastFuzz = fuzzes.length;
- for (var i = 1; i <= last; i++) {
- msg = "";
- for (var j = 0; j < lastFuzz; j++) {
- if (0 == i%fuzzNums[j]) msg += fuzzes[j];
- }
- rpt.push(("" == msg)?"" + i:msg);
- }
- return rpt;
- };
- Classical FizzBuzz is:
- Fuzz( ["Fizz", "Buzz"], [3, 5], 100 )
- For wackier fun, try
- Fuzz( ["Fizz", "Buzz", "Your", "Mama"], [3, 5, 7, 11], 3*5*7*11 )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement