24 game/Solve: Difference between revisions

→‎{{header|Ruby}}: used suffix r (Rational) and Array#product
m (fixed typo)
(→‎{{header|Ruby}}: used suffix r (Rational) and Array#product)
Line 4,946:
=={{header|Ruby}}==
{{trans|Tcl}}
{{works with|Ruby|2.1}}
<lang ruby>class TwentyFourGamePlayerTwentyFourGame
EXPRESSIONS = [
'((%ddr %s %ddr) %s %ddr) %s %ddr',
'(%ddr %s (%ddr %s %ddr)) %s %ddr',
'(%ddr %s %ddr) %s (%ddr %s %ddr)',
'%ddr %s ((%ddr %s %ddr) %s %ddr)',
'%ddr %s (%ddr %s (%ddr %s %ddr))',
]
].map{|expr| [expr, expr.gsub('%d', 'Rational(%d,1)')]}
OPERATORS = [:+, :-, :*, :/].repeated_permutation(3).to_a
OBJECTIVE = Rational(24,1)
def self.solve(digits)
solutions = []
perms = digits.permutation.to_a.uniq.each do |a,b,c,d|
OPERATORSperms.eachproduct(OPERATORS, EXPRESSIONS) do |(a,b,c,d), (op1,op2,op3), expr|
# evaluate using rational arithmetic
EXPRESSIONS.each do |expr,expr_rat|
text = expr % #[a, evaluateop1, usingb, rationalop2, arithmeticc, op3, d]
value = eval(testtext) rescue -1next # catch division by zero
test = expr_rat % [a, op1, b, op2, c, op3, d]
solutions << text.delete("r") if value == 24
value = eval(test) rescue -1 # catch division by zero
if value == OBJECTIVE
solutions << expr % [a, op1, b, op2, c, op3, d]
end
end
end
end
solutions
Line 4,987 ⟶ 4,981:
digits.size == 4 or raise "error: need 4 digits, only have #{digits.size}"
 
solutions = TwentyFourGamePlayerTwentyFourGame.solve(digits)
if solutions.empty?
puts "no solutions"
Line 4,996 ⟶ 4,990:
 
{{out}}
<pre>$ ruby 24game.playergame24_solver.rb 1 1 1 1
no solutions
 
$ ruby 24game.playergame24_solver.rb 1 1 2 7
found 8 solutions, including (1 + 2) * (1 + 7)
(1 + 2) * (1 + 7)
Line 5,010 ⟶ 5,004:
(7 + 1) * (2 + 1)
 
$ ruby 24game.playergame24_solver.rb 2 3 8 9
found 12 solutions, including (8 / 2) * (9 - 3)
((9 - 3) * 8) / 2
Anonymous user