Skip to content

Instantly share code, notes, and snippets.

@joshfreemanIO
Last active August 29, 2015 14:21
Show Gist options
  • Save joshfreemanIO/b2475a8f130189fe333f to your computer and use it in GitHub Desktop.
Save joshfreemanIO/b2475a8f130189fe333f to your computer and use it in GitHub Desktop.
FizzBuzz without Conditional Control Structures
def fizz_buzz(start, final)
set = {}
normal_values = [*start..final]
fizz_values = [*((start - start % 3)..final).step(3)]
buzz_values = [*((start - start % 5)..final).step(5)]
fizz_buzz_values = [*((start - start % 15)..final).step(15)]
normal_values.each do |number|
set[number] = number
end
fizz_values.each do |number|
set[number] = 'Fizz'
end
buzz_values.each do |number|
set[number] = 'Buzz'
end
fizz_buzz_values.each do |number|
set[number] = 'FizzBuzz'
end
set.sort.to_h.values[start..final]
end
def fizz_buzz_with_reject(start, final)
set = {}
fizz_values = (start..final).select { |n| n % 3 == 0 }
buzz_values = (start..final).select { |n| n % 5 == 0 }
fizz_buzz_values = (start..final).select { |n| n % 3 == 0 && n % 5 == 0 }
(start..final).each do |number|
set[number] = number
end
fizz_values.each do |number|
set[number] = 'Fizz'
end
buzz_values.each do |number|
set[number] = 'Buzz'
end
fizz_buzz_values.each do |number|
set[number] = 'FizzBuzz'
end
set.values
end
require_relative 'fizz_buzz'
require 'minitest/autorun'
class FizzBuzzTest < MiniTest::Test
CANON = ['FizzBuzz', 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']
def test_zero_to_thirty
assert_equal(CANON[0..30], fizz_buzz(0,30))
end
def test_one_to_thirty
assert_equal(CANON[1..30], fizz_buzz(1,30))
end
def test_zero_to_twenty_nine
assert_equal(CANON[0..29], fizz_buzz(0,29))
end
def test_one_to_twenty_nine
assert_equal(CANON[1..29], fizz_buzz(1,29))
end
def test_zero_to_thirty_with_reject
assert_equal(CANON[0..30], fizz_buzz_with_reject(0,30))
end
def test_one_to_thirty_with_reject
assert_equal(CANON[1..30], fizz_buzz_with_reject(1,30))
end
def test_zero_to_twenty_nine_with_reject
assert_equal(CANON[0..29], fizz_buzz_with_reject(0,29))
end
def test_one_to_twenty_nine_with_reject
assert_equal(CANON[1..29], fizz_buzz_with_reject(1,29))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment