Skip to content

Instantly share code, notes, and snippets.

@cympfh
Last active March 4, 2016 13:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cympfh/ea3a448aa841fe62bf9e to your computer and use it in GitHub Desktop.
Save cympfh/ea3a448aa841fe62bf9e to your computer and use it in GitHub Desktop.
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