Jump to content

24 game/Solve: Difference between revisions

add Ruby
(add Ruby)
Line 294:
(3+(5+4))), (4*(5+(3-2))), (4*(3+(5-2))), (4*(3-(2-5))))
</pre>
 
=={{header|Ruby}}==
{{trans|Tcl}}
<lang ruby>class TwentyFourGamePlayer
EXPRESSIONS = [
'a.send(op1, b).send(op2, c).send(op3, d)', # '((a op1 b) op2 c) op3 d',
'a.send(op1, b.send(op2, c)).send(op3, d)', # '(a op1 (b op2 c)) op3 d',
'a.send(op1, b).send(op2, c.send(op3, d))', # '(a op1 b) op2 (c op3 d)',
'a.send(op1, b.send(op2, c).send(op3, d))', # 'a op1 ((b op2 c) op3 d)',
'a.send(op1, b.send(op2, c.send(op3, d)))', # 'a op1 (b op2 (c op3 d))',
]
PRINT_FORMATS = [
'((%d %s %d) %s %d) %s %d',
'(%d %s (%d %s %d)) %s %d',
'(%d %s %d) %s (%d %s %d)',
'%d %s ((%d %s %d) %s %d)',
'%d %s (%d %s (%d %s %d))',
]
OPERATORS = [:+, :-, :*, :/]
@@objective = 24.0
 
def initialize(digits)
@digits = digits.collect {|digit| digit.to_f}
@solutions = []
solve
end
 
attr_reader :digits, :solutions
 
def solve
digits.permutation.to_a.uniq.each do |a,b,c,d|
OPERATORS.each do |op1|
OPERATORS.each do |op2|
OPERATORS.each do |op3|
EXPRESSIONS.each_with_index do |expr, i|
if eval(expr) == @@objective
@solutions << PRINT_FORMATS[i] % [a, op1, b, op2, c, op3, d]
end
end
end
end
end
end
end
end
 
digits = ARGV.map {|arg| arg.to_i}
player = TwentyFourGamePlayer.new(digits)
if player.solutions.empty?
puts "no solutions"
else
puts "found #{player.solutions.size} solutions, including #{player.solutions.first}"
puts player.solutions.sort.join("\n")
end</lang>
 
Sample output:
<pre>$ ruby 24game.player.rb 1 1 1 1
no solutions
 
$ ruby 24game.player.rb 1 1 2 7
found 8 solutions, including (1 + 2) * (1 + 7)
(1 + 2) * (1 + 7)
(1 + 2) * (7 + 1)
(1 + 7) * (1 + 2)
(1 + 7) * (2 + 1)
(2 + 1) * (1 + 7)
(2 + 1) * (7 + 1)
(7 + 1) * (1 + 2)
(7 + 1) * (2 + 1)
 
$ ruby 24game.player.rb 2 3 8 9
found 12 solutions, including (8 / 2) * (9 - 3)
((9 - 3) * 8) / 2
((9 - 3) / 2) * 8
(8 * (9 - 3)) / 2
(8 / 2) * (9 - 3)
(9 - (2 * 3)) * 8
(9 - (3 * 2)) * 8
(9 - 3) * (8 / 2)
(9 - 3) / (2 / 8)
8 * ((9 - 3) / 2)
8 * (9 - (2 * 3))
8 * (9 - (3 * 2))
8 / (2 / (9 - 3))</pre>
 
=={{header|Tcl}}==
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.