24 game/Solve: Difference between revisions

Added Elixir
(→‎{{header|Ruby}}: used suffix r (Rational) and Array#product)
(Added Elixir)
Line 1,532:
(5 9 7 3 6 3) → -54
-54 = 9 * (7 + (6 - 5 * 3)) * 3 tries= 2576
</pre>
 
=={{header|Elixir}}==
{{trans|Ruby}}
<lang elixir>defmodule Game24 do
@expressions [ ["((", "", ")", "", ")", ""],
["(", "(", "", "", "))", ""],
["(", "", ")", "(", "", ")"],
["", "((", "", "", ")", ")"],
["", "(", "", "(", "", "))"] ]
def solve(digits) do
dig_perm = permute(digits) |> Enum.uniq
operators = perm_rep(~w[+ - * /], 3)
Enum.reduce(dig_perm, [], fn dig,acc ->
Enum.reduce(operators, acc, fn ope,ac2 ->
Enum.reduce(@expressions, ac2, fn expr,ac3 ->
str = make_expr(dig, ope, expr)
try do
{val, _} = Code.eval_string(str)
if val == 24, do: [str | ac3], else: ac3
rescue
ArithmeticError -> ac3 # division by zero
end
end)
end)
end)
end
defp permute([]), do: [[]]
defp permute(list) do
for x <- list, y <- permute(list -- [x]), do: [x|y]
end
defp perm_rep([], _), do: [[]]
defp perm_rep(_, 0), do: [[]]
defp perm_rep(list, i) do
for x <- list, y <- perm_rep(list, i-1), do: [x|y]
end
defp make_expr([a,b,c,d], [x,y,z], [e0,e1,e2,e3,e4,e5]) do
e0 <> a <> x <> e1 <> b <> e2 <> y <> e3 <> c <> e4 <> z <> d <> e5
end
end
 
case Game24.solve(System.argv) do
[] -> IO.puts "no solutions"
solutions ->
IO.puts "found #{length(solutions)} solutions, including #{hd(solutions)}"
IO.inspect Enum.sort(solutions)
end</lang>
 
{{out}}
<pre>
C:\Elixir>elixir game24.exs 1 1 3 4
found 12 solutions, including 4*(3*(1+1))
["((1+1)*3)*4", "((1+1)*4)*3", "(1+1)*(3*4)", "(1+1)*(4*3)", "(3*(1+1))*4",
"(3*4)*(1+1)", "(4*(1+1))*3", "(4*3)*(1+1)", "3*((1+1)*4)", "3*(4*(1+1))",
"4*((1+1)*3)", "4*(3*(1+1))"]
C:\Elixir>elixir game24.exs 6 7 8 9
found 8 solutions, including 8/((9-7)/6)
["(6*8)/(9-7)", "(6/(9-7))*8", "(8*6)/(9-7)", "(8/(9-7))*6", "6*(8/(9-7))",
"6/((9-7)/8)", "8*(6/(9-7))", "8/((9-7)/6)"]
C:\Elixir>elixir game24.exs 1 2 2 3
no solutions
</pre>
 
Line 1,866 ⟶ 1,931:
Total= 12
</pre>
 
=={{header|Euler Math Toolbox}}==
 
Line 1,917 ⟶ 1,983:
3-4=-1
</lang>
 
 
=={{header|F_Sharp|F#}}==
Line 5,596 ⟶ 5,661:
...
</pre>
 
 
{{omit from|GUISS}}
{{omit from|ML/I}}
 
[[Category:Puzzles]]
Anonymous user