Skip to content

Instantly share code, notes, and snippets.

@hyuki
Created May 31, 2019 01:01
Show Gist options
  • Save hyuki/04df2799f21c8fc97aca16b45222f63b to your computer and use it in GitHub Desktop.
Save hyuki/04df2799f21c8fc97aca16b45222f63b to your computer and use it in GitHub Desktop.
stairs.rb - 階段昇降
# 毎日『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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment