Last active
August 31, 2016 13:30
-
-
Save mcelaney/50151494110fc6465a800ae54c30d004 to your computer and use it in GitHub Desktop.
When brevity doesn't matter...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Run if necessary: | |
# RubyVM::InstructionSequence.compile_option = { | |
# tailcall_optimization: true, | |
# trace_instruction: false | |
# } | |
class FizzBuzz | |
def self.find_answers_for(max) | |
self.new(max).find_answers_for([], 1) | |
end | |
def initialize(max) | |
@max = max | |
@fizz = 1 | |
@buzz = 1 | |
@fizzbuzz = 1 | |
end | |
def find_answers_for(acc, count) | |
return acc if count > @max | |
result = compute(count) | |
advance_state | |
find_answers_for( | |
acc << result, | |
count + 1 | |
) | |
end | |
private | |
def advance_state | |
advance_fizz | |
advance_buzz | |
advance_fizzbuzz | |
nil | |
end | |
def advance_fizz | |
@fizz = @fizz == 3 ? 1 : @fizz + 1 | |
end | |
def advance_buzz | |
@buzz = @buzz == 5 ? 1 : @buzz + 1 | |
end | |
def advance_fizzbuzz | |
@fizzbuzz = @fizzbuzz == 15 ? 1 : @fizzbuzz + 1 | |
end | |
def compute(count) | |
if @fizzbuzz == 15 | |
"fizzbuzz" | |
elsif @buzz == 5 | |
"buzz" | |
elsif @fizz == 3 | |
"fizz" | |
else | |
count.to_s | |
end | |
end | |
end | |
puts Benchmark.measure { FizzBuzz.find_answers_for(10000) } | |
# 0.400000 0.030000 0.430000 ( 0.422816) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment