Advertisement
richarduie

FizzBuzz

Oct 17th, 2013
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.03 KB | None | 0 0
  1. So, I ran across the "FizzBuzz" interview question in a geek article at Los Techies:
  2.  
  3. http://lostechies.com/jimmybogard/2013/01/29/fizzbuzz-is-dead-long-live-fizzbuzz
  4.  
  5. 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.
  6.  
  7. function FizzBuzz(fizz, buzz, fizzNum, buzzNum, last) {
  8. var msgs = [0, fizz, buzz, fizz + buzz];
  9. var rpt = new Array();
  10. for (var i = 1; i <= last; i++) {
  11. msgs[0] = "" + i;
  12. rpt.push(msgs[((0 == i%fizzNum)?1:0) + ((0 == i%buzzNum)?2:0)]);
  13. }
  14. return rpt;
  15. };
  16.  
  17. The "standard answer" is given by the call:
  18.  
  19. FizzBuzz("Fizz", "Buzz", 3, 5, 100)
  20.  
  21. The expression
  22.  
  23. ((0 == i%fizzNum)?1:0) + ((0 == i%buzzNum)?2:0)
  24.  
  25. implements the following partition of the decision universe and the corresponding numerical results:
  26.  
  27. Fizz Buzz
  28. i divisible i divisible
  29. by fizzNum by buzzNum Fizz + Buzz
  30. ----------- ----------- ------------------------
  31. F => 0 F => 0 0 + 0 = 0 => "" + i
  32. T => 1 F => 0 1 + 0 = 1 => fizz
  33. F => 0 T => 2 0 + 2 = 2 => buzz
  34. T => 1 T => 2 1 + 2 = 3 => fizz + buzz
  35.  
  36.  
  37. 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.
  38.  
  39. Ah, OCD! Okay, one more generalization of the FizzBuzz notion...
  40.  
  41. function Fuzz(fuzzes, fuzzNums, last) {
  42. var msg;
  43. var rpt = new Array();
  44. var lastFuzz = fuzzes.length;
  45. for (var i = 1; i <= last; i++) {
  46. msg = "";
  47. for (var j = 0; j < lastFuzz; j++) {
  48. if (0 == i%fuzzNums[j]) msg += fuzzes[j];
  49. }
  50. rpt.push(("" == msg)?"" + i:msg);
  51. }
  52. return rpt;
  53. };
  54.  
  55. Classical FizzBuzz is:
  56.  
  57. Fuzz( ["Fizz", "Buzz"], [3, 5], 100 )
  58.  
  59. For wackier fun, try
  60.  
  61. Fuzz( ["Fizz", "Buzz", "Your", "Mama"], [3, 5, 7, 11], 3*5*7*11 )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement