Skip to content

Instantly share code, notes, and snippets.

@RedFred7
Created May 7, 2015 21:58
Show Gist options
  • Save RedFred7/3da28faccd818f1a52da to your computer and use it in GitHub Desktop.
Save RedFred7/3da28faccd818f1a52da to your computer and use it in GitHub Desktop.
3 approaches to solving FizzBuzz
require 'benchmark'
# using simple conditional statements
def conditional(n)
if (n % 3 == 0) && (n % 5 != 0)
'Fizz'
elsif (n % 3 != 0) && (n % 5 == 0)
'Buzz'
elsif (n % 3 == 0) && (n % 5 == 0)
'FizzBuzz'
else n
end
end
# no conditionals, just boolean logic
def declarative(n)
h = {
'Fizz' => (n % 3 == 0) && (n % 5 != 0),
'Buzz' => (n % 3 != 0) && (n % 5 == 0),
'FizzBuzz' => (n % 3 == 0) && (n % 5 == 0),
n => (n % 3 != 0) && (n % 5 != 0)
}
h.key(true)
end
# conditionals used first time to build up the hash,
# after that it's just a hash look-up
memoization ||= Hash.new do |hash,key|
hash[key] = case
when (key % 3 == 0) && (key % 5 != 0)
'Fizz'
when (key % 3 != 0) && (key % 5 == 0)
'Buzz'
when (key % 3 == 0) && (key % 5 == 0)
'FizzBuzz'
else key
end
end
r = (1..1_000_000)
Benchmark.bm do |bm|
bm.report(:conditional) { r.each { |n| conditional(n) }}
bm.report(:conditional) { r.each { |n| conditional(n) }}
bm.report(:declarative) { r.each { |n| declarative(n) }}
bm.report(:declarative) { r.each { |n| declarative(n) }}
bm.report(:memoization) { r.each { |n| memoization[n] }}
bm.report(:memoization) { r.each { |n| memoization[n] }}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment