Different levels of FizzBuzz (using Ruby)

in #programming3 years ago

If you are old enough like me, you probably already did (or make pass) a FizzBuzz exercise during an interview.
I don't think it is still used anymore but it used to be a classic.

So let's grab a beer and start coding.

First implementations

The first implementation here is the basic one, it works fine and is pretty much the same on every language.

1.upto(100) do |i|
  if i % 3 == 0 && i % 5 == 0
    puts 'FizzBuzz'
  elsif i % 3 == 0
    puts 'Fizz'
  elsif i % 5 == 0
    puts 'Buzz'
  else
    puts i
  end
end

But we can get rid of one useless if statement.
Some people would say that the ternary operator is not that much readable and
prefer using a boolean but both solutions are totally fine for me.

1.upto(100) do |i|
  result = ''
  if i % 3 == 0
    result += 'Fizz'
  end
  if i % 5 == 0
    result += 'Buzz'
  end

  puts result == '' ? i : result
end

Finally if the developer is familiar with the language, he should write more "idiomatic" code, Ruby in our case :

1.upto(100) do |i|
  result = ''
  result += 'Fizz' if (i % 3).zero?
  result += 'Buzz' if (i % 5).zero?

  puts result.empty? ? i : result
end

Use a datastructure

What if we need to extends this code ?
What if I want to add another prime number, for example 7 is 'Bazz'?
The next level for this exercise should be to use a datastructure, like a dictionary in python or a hash in ruby.

FIZZ_BUZZ = {
  fizz: 3,
  buzz: 5
}

1.upto(100) do |i|
  result = ''
  FIZZ_BUZZ.map do |text, divisor|
    result += text.to_s.capitalize if (i % divisor).zero?
  end

  puts result.empty? ? i : result
end

Use lambdas

For our last version, let's use a lambda and move our modulo predicate to the hash

FIZZ_BUZZ = {
  fizz: ->(i) { (i % 3).zero? },
  buzz: ->(i) { (i % 5).zero? }
}

1.upto(100) do |i|
  result = ''
  FIZZ_BUZZ.map do |text, predicate|
    result += text.to_s.capitalize if predicate.call(i)
  end

  puts result.empty? ? i : result
end

Bonus point: machine learning :)

A crazy guy implemented a solution using machine learning
check it out, it's really fun.