Last active
May 31, 2019 01:04
-
-
Save hyuki/bebb73b7fb3379f55e872526ea77c288 to your computer and use it in GitHub Desktop.
stairs.rb - 階段昇降
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 | |
# current段目から「m段上ってn段下がる」ときに通過する | |
# 「段目」を引数にブロックをyieldして | |
# 最終的な段目を戻り値に | |
def daily(current,m,n) | |
m.times do | |
current += 1 | |
yield current | |
end | |
n.times do | |
current -= 1 | |
yield current | |
end | |
current | |
end | |
# 0段目から毎日「m段上ってn段下がる」 | |
# ことを繰り返して最初にd段目にきたときに何日目であるかを答える | |
# m > n > 0, d > 0 を仮定 | |
def updown(m,n,d) | |
x = nil | |
current = 0 | |
day = 1 | |
loop do | |
print "#{day}日目:" | |
current = daily(current, m, n) do |c| | |
print "#{c}" | |
if not x | |
if c == d | |
print "*" | |
x = day | |
end | |
end | |
print "," | |
end | |
puts | |
if x | |
puts "#{m}段上って#{n}段下るなら、#{d}段目に#{x}日目に到着" | |
break | |
end | |
day += 1 | |
end | |
puts | |
end | |
updown(3, 2, 15) | |
updown(15, 14, 15) |
Author
hyuki
commented
May 31, 2019
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment