Create a gist now

Instantly share code, notes, and snippets.

@cympfh /README
Last active Mar 4, 2016

Make 10, 四則パズル
与えられた数を順不同に用い、四則を自由な順に適用して10を作るパズル
ANS=10.0
def dfs(a)
if a.size == 1
puts a[0][:exp] if a[0][:val] == ANS
return
end
(0...a.size).each {|i|
((i+1)...a.size).each {|j|
rest = []
(0...a.size).each {|idx|
rest << a[idx] if idx!=i && idx!=j
}
x = a[i]
y = a[j]
dfs [ { :val => x[:val] + y[:val], :exp => "(+ #{x[:exp]} #{y[:exp]})" } ] + rest
dfs [ { :val => x[:val] * y[:val], :exp => "(* #{x[:exp]} #{y[:exp]})" } ] + rest
dfs [ { :val => x[:val] - y[:val], :exp => "(- #{x[:exp]} #{y[:exp]})" } ] + rest
dfs [ { :val => y[:val] - x[:val], :exp => "(- #{y[:exp]} #{x[:exp]})" } ] + rest
dfs [ { :val => x[:val] / y[:val], :exp => "(/ #{x[:exp]} #{y[:exp]})" } ] + rest
dfs [ { :val => y[:val] / x[:val], :exp => "(/ #{y[:exp]} #{x[:exp]})" } ] + rest
}
}
end
def solve(ls)
dfs ls.map {|x| { :val => x.to_f, :exp => x.to_s } }
end
solve [1,1,5,8]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment