Skip to content

Instantly share code, notes, and snippets.

@hakobe
Created February 3, 2010 05:51
Show Gist options
  • Select an option

  • Save hakobe/293365 to your computer and use it in GitHub Desktop.

Select an option

Save hakobe/293365 to your computer and use it in GitHub Desktop.
# ホワイトボードに書いてあった問題:
# o/oo + o/oo + o/oo = 1
# o の部分には 1..9 の数字が一つづつ入る
#
# だめな例:
# 1/23 + 4/56 + 7/89 = 0.19355... != 1 => だめぽ
#
def traverse(remain, result=[])
calc(result) if remain.empty?
remain.each {|n| traverse(remain - [n] , result + [n])}
end
def calc(r)
d1 = r[1]*10+r[2]
d2 = r[4]*10+r[5]
d3 = r[7]*10+r[8]
t1 = r[0] * d2 * d3
t2 = r[3] * d1 * d3
t3 = r[6] * d1 * d2
print_result r if d1*d2*d3 == t1+t2+t3
end
def print_result(r)
puts "#{r[0]}/#{r[1]*10+r[2]} + " +
"#{r[3]}/#{r[4]*10+r[5]} + " +
"#{r[6]}/#{r[7]*10+r[8]}"
end
traverse((1..9).to_a)
# $ time ruby q1.rb
# 5/34 + 7/68 + 9/12
# 5/34 + 9/12 + 7/68
# 7/68 + 5/34 + 9/12
# 7/68 + 9/12 + 5/34
# 9/12 + 5/34 + 7/68
# 9/12 + 7/68 + 5/34
# ruby q1.rb 5.04s user 0.02s system 92% cpu 5.464 total
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment