How to advance multiple Enumerators, or “But what about FizzBuzzBoozz?”
-
08-10-2019 - |
Question
This is a rather unorthodox way to do the classic FizzBuzz exercise, but it's just to illustrate the problem (and hey, it might be fast if you want to fizzbuzz to a billion).
fizzer = ( Array.new( 2, '' ) << 'Fizz' ).cycle
buzzer = ( Array.new( 4, '' ) << 'Buzz' ).cycle
(1..100).each do |number|
fizzbuzz = fizzer.next + buzzer.next # this line is giving me problems.
puts ( fizzbuzz.empty? ? number : fizzbuzz )
end
How to generalize this code to accept a hash like {3 => 'Fizz', 5 => 'Buzz', 7 => 'Boozz'} ?
Solution
Create an array of Fizzers, Buzzers, and Boozzers. Then in the loop call next
on each fooer in that array and then sum the results with inject
:
# The sort is needed so it prints fizzbuzz, not buzzfizz
# (hashes being unordered and all)
fooers = the_hash.sort_by {|k,v| k}.map do |k,v|
( Array.new(k - 1, '') << v ).cycle
end
(1..100).each do |number|
fizzbuzz = fooers.map(&:next).inject(:+)
puts ( fizzbuzz.empty? ? number : fizzbuzz )
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow