DEV Community

QUANON
QUANON

Posted on • Edited on

Lazy FizzBuzz

I though up this Fizz Buzz suddenly when I was about to go to the bathroom. So I made this note ๐Ÿ˜‡

def genarate_lazy_list(number, yell)
  [*Array.new(number - 1, nil), yell].cycle
end

numbers = 1.step.lazy
fizzes = genarate_lazy_list(3,'Fizz')
buzzes = genarate_lazy_list(5,'Buzz')
fizzbuzzes = genarate_lazy_list(15,'FizzBuzz')

# Add backslash for irb. I prefer leading dots to trailing ones.
numbers \
  .zip(fizzes, buzzes, fizzbuzzes) \
  .map { |n, fizz, buzz, fizzbuzz| fizzbuzz || buzz || fizz || n } \
  .take(30) \
  .each(&method(:puts))
Enter fullscreen mode Exit fullscreen mode
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz
Fizz
22
23
Fizz
Buzz
26
Fizz
28
29
FizzBuzz
Enter fullscreen mode Exit fullscreen mode

Top comments (5)

Collapse
 
quanon profile image
QUANON

I thought up more declarative one.

def say(fizzbuzz)
  def fizzbuzz.for_multiples_of(number)
    loop.lazy.flat_map { [*Array.new(number - 1, nil), self] }
  end

  fizzbuzz
end

fizzes = say('Fizz').for_multiples_of(3)
buzzes = say('Buzz').for_multiples_of(5)
Collapse
 
hanachin profile image
Seiei Miyagi • Edited

Awesome! zipping infinite generators is really cool๐Ÿ‘

Tips: Array#cycle can be used to generate infinite sequence of Fizz and Buzz.

numbers = 1.step
fizzes = [nil, nil, "Fizz"].cycle
buzzes = [nil, nil, nil, nil, "Buzz"].cycle

numbers \
  .lazy \
  .zip(fizzes, buzzes) \
  .map { |n, *yells| yells.any? ? yells.join : n } \
  .take(30) \
  .each(&method(:puts))
Collapse
 
quanon profile image
QUANON

Thank you! The method makes it simpler ๐Ÿ’ช

Collapse
 
quanon profile image
QUANON

Everybody who fizzes the buzzes misses that fizzbuzz entity is redundant:

You're right โœจ Thank you for your reply ๐Ÿ’–

Collapse
 
quanon profile image
QUANON • Edited

Object#presence (in Active Support Core Extensions) makes it simpler ๐Ÿ˜„

require 'active_support'
require 'active_support/core_ext/object/blank'

numbers \
  .zip(fizzes, buzzes) \
  .map { |n, fizz, buzz| "#{fizz}#{buzz}".presence || n } \
  .take(30) \
  .each(&method(:puts))