DZone 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

Snippets has posted 5883 posts at DZone. View Full User Profile

FizzBuzz

03.23.2007
| 4131 views |
  • submit to reddit
        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.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:

class FizzBuzz

  def initialize(start_number, end_number)
    @starting = start_number
    @ending = end_number
    @phrase_multiples = []
  end

  def add_phrase_multiple(phrase, multiple)
    @phrase_multiples << [phrase, multiple]
  end

  def print_phrases
    fb_array = process_phrases
    puts fb_array.collect { |e| e[1] || e[0] }.join("\n")
  end

  private

  def process_phrases
    rarray = Array.new(@ending - @starting)
    rarray = rarray.each_with_index { |item, i| rarray[i] = [i + @starting, item] }
    @phrase_multiples.each { |pm| fill_multiples(rarray, pm[1], pm[0]) }
    rarray
  end

  def fill_multiples(fill_array, the_int, printed)
    (the_int - (fill_array[0][0] % the_int)).step(fill_array.size - 1, the_int) do |i|
      fill_array[i][1] = fill_array[i][1].to_s + printed.to_s
    end
  end

end

fb = FizzBuzz.new(1,100)
fb.add_phrase_multiple('fizz', 3)
fb.add_phrase_multiple('buzz', 5)
fb.print_phrases