The classic solution to Fizz Buzz
uses Euclidean division, or the modulo operator (% in Ruby). But we can solve
it without the modulo.
Here’s Fizz Buzz in Ruby with no modulo. Instead, it uses a running counter,
which we can compare to 3 and 5. When equal to one or both, we print one of
those special Fizz Buzz strings.
# fizz_buzz.rb
three_count = 0
five_count = 0
# Any range will do.
(1..20).each do |number|
# Increment both counters on each iteration.
three_count += 1
five_count += 1
output = if three_count == 3 && five_count == 5
'Fizz Buzz'
elsif three_count == 3
'Fizz'
elsif five_count == 5
'Buzz'
else
number
end
# Reset counters if there was a match.
three_count = 0 if three_count == 3
five_count = 0 if five_count == 5
puts output
end
And the output:
$ ruby fizz_buzz.rb
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
Fizz Buzz
16
17
Fizz
19
Buzz
Thinking about classic problems with novel constraints is a great way to level up. It’s kind of like walking with a weight vest on. I found such a list online of such constraints, and I plan to explore it.
In this case, I’m glad I learned a new way to solve a problem I thought there was only one reasonable solution to. Practically, I think using division is easier to scan.