Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Scott Chacon

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

FizzBuzz

This is pretty stupid, but it's a response to the article recently Dugg here:
http://www.codinghorror.com/blog/archives/000781.html

It is about how a lot of job applicants have a hard time actually programming. My friend and I were amused by it and started going back and forth with different implementations until it got to this point.

The problem is:

'Write a program that prints the numbers from 1 to 100. But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz".'

Now, it can be done like this:
   1  
   2  1.upto(100) { |n| puts n % 3 == 0 ? n % 5 == 0 ? "fizzbuzz" : "buzz" : n % 5 == 0 ? "fizz" : n }


But, this is what I ended up with, which turns out actually to be faster and obviously far more flexible:

   1  
   2  class FizzBuzz
   3  
   4    def initialize(start_number, end_number)
   5      @starting = start_number
   6      @ending = end_number
   7      @phrase_multiples = []
   8    end
   9  
  10    def add_phrase_multiple(phrase, multiple)
  11      @phrase_multiples << [phrase, multiple]
  12    end
  13  
  14    def print_phrases
  15      fb_array = process_phrases
  16      puts fb_array.collect { |e| e[1] || e[0] }.join("\n")
  17    end
  18  
  19    private
  20  
  21    def process_phrases
  22      rarray = Array.new(@ending - @starting)
  23      rarray = rarray.each_with_index { |item, i| rarray[i] = [i + @starting, item] }
  24      @phrase_multiples.each { |pm| fill_multiples(rarray, pm[1], pm[0]) }
  25      rarray
  26    end
  27  
  28    def fill_multiples(fill_array, the_int, printed)
  29      (the_int - (fill_array[0][0] % the_int)).step(fill_array.size - 1, the_int) do |i|
  30        fill_array[i][1] = fill_array[i][1].to_s + printed.to_s
  31      end
  32    end
  33  
  34  end
  35  
  36  fb = FizzBuzz.new(1,100)
  37  fb.add_phrase_multiple('fizz', 3)
  38  fb.add_phrase_multiple('buzz', 5)
  39  fb.print_phrases
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS