Skip to content

Instantly share code, notes, and snippets.

@yamaimo
Last active June 1, 2019 02:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yamaimo/c2b1c472dd2adf1abe01eb1f56aba9a7 to your computer and use it in GitHub Desktop.
Save yamaimo/c2b1c472dd2adf1abe01eb1f56aba9a7 to your computer and use it in GitHub Desktop.
階段昇降
# 毎日『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