Skip to content
loading...

Lazy FizzBuzz

twitter logo github logo Updated on ・1 min read  

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))
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
twitter logo DISCUSS (7)
markdown guide
 

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

def genarate_lazy_list(number, yell)
  loop.lazy.flat_map { [*Array.new(number - 1, nil), yell] }
end

numbers = (1..Float::INFINITY).lazy
fizzes = genarate_lazy_list(3,'Fizz')
buzzes = genarate_lazy_list(5,'Buzz')

# Add backslash for irb.
numbers \
  .zip(fizzes, buzzes) \
  .map { |n, fizz, buzz| "#{fizz}#{buzz}".tap { |s| s << n.to_s if s.empty? }} \
  .take(30) \
  .force \
  .each(&method(:puts))

Besides that the solution is neat and nifty :)

 

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

You're right ✨ Thank you for your reply 💖

 

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))

Nah :)

I am trying to avoid Rails whenever possible.

 

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))
 

Thank you! The method makes it simpler 💪

 

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)
Classic DEV Post from Jun 30 '18

What each sorting algorithm is good for

Some nice properties of sorting algorithms many don't aware of

QUANON profile image
I'm a Rubyrist and want to be a Pythonista. I love Puella Magi Madoka Magica.