Skip to content

Instantly share code, notes, and snippets.

@hyuki
Last active May 31, 2019 01:04
Show Gist options
  • Save hyuki/bebb73b7fb3379f55e872526ea77c288 to your computer and use it in GitHub Desktop.
Save hyuki/bebb73b7fb3379f55e872526ea77c288 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)
@hyuki
Copy link
Author

hyuki commented May 31, 2019

1日目:1,2,3,2,1,
2日目:2,3,4,3,2,
3日目:3,4,5,4,3,
4日目:4,5,6,5,4,
5日目:5,6,7,6,5,
6日目:6,7,8,7,6,
7日目:7,8,9,8,7,
8日目:8,9,10,9,8,
9日目:9,10,11,10,9,
10日目:10,11,12,11,10,
11日目:11,12,13,12,11,
12日目:12,13,14,13,12,
13日目:13,14,15*,14,13,
3段上って2段下るなら、15段目に13日目に到着

1日目:1,2,3,4,5,6,7,8,9,10,11,12,13,14,15*,14,13,12,11,10,9,8,7,6,5,4,3,2,1,
15段上って14段下るなら、15段目に1日目に到着

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment