Last active
March 4, 2016 13:41
-
-
Save cympfh/ea3a448aa841fe62bf9e to your computer and use it in GitHub Desktop.
Make 10, 四則パズル
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
与えられた数を順不同に用い、四則を自由な順に適用して10を作るパズル |
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
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