Last active
June 1, 2019 02:41
-
-
Save yamaimo/c2b1c472dd2adf1abe01eb1f56aba9a7 to your computer and use it in GitHub Desktop.
階段昇降
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
# 毎日『m段上ってn段下がる』を繰り返したら、x日目にd段目に初めて着いた。 | |
# xをd,m,nで表せ。 | |
# 文字はすべて正の整数で、m>nとする。 | |
# https://twitter.com/hyuki/status/1134018952416321536 | |
class Stairs | |
def initialize(dest, up, down) | |
@dest = dest | |
@up = up | |
@down = down | |
end | |
def to_s | |
"d=#{@dest}, m=#{@up}, n=#{@down}" | |
end | |
def solve | |
[1, Rational(@dest - @down, @up - @down).ceil].max | |
end | |
def simulate(verbose=true) | |
day = 0 | |
current = 0 | |
done = false | |
until done | |
day += 1 | |
print "#{day}日目: " if verbose | |
step = [] | |
@up.times do | |
current += 1 | |
step.push current | |
if current >= @dest | |
done = true | |
break | |
end | |
end | |
unless done | |
@down.times do | |
current -= 1 | |
step.push current | |
end | |
end | |
puts step.join(', ') if verbose | |
end | |
day | |
end | |
end | |
def test(dest, up, down) | |
problem = Stairs.new(dest, up, down) | |
puts problem.to_s | |
answer = problem.solve | |
puts "x=#{answer}" | |
simulated = problem.simulate | |
raise "wrong answer." if answer != simulated | |
end | |
test(7, 5, 4) | |
test(7, 5, 2) | |
test(7, 8, 6) | |
test(7, 11, 8) | |
test(15, 3, 2) | |
test(15, 15, 14) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment