24 game/Solve: Difference between revisions

Content added Content deleted
m (alphabetized)
Line 240: Line 240:
{{trans|Tcl}}
{{trans|Tcl}}
<lang ruby>class TwentyFourGamePlayer
<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 = [
PRINT_FORMATS = [
'((%d %s %d) %s %d) %s %d',
'((%d %s %d) %s %d) %s %d',
Line 271: Line 264:
OPERATORS.each do |op2|
OPERATORS.each do |op2|
OPERATORS.each do |op3|
OPERATORS.each do |op3|
EXPRESSIONS.each_with_index do |expr, i|
PRINT_FORMATS.each do |expr|
if eval(expr) == @@objective
# change to floats so it does floating-point division
@solutions << PRINT_FORMATS[i] % [a, op1, b, op2, c, op3, d]
test = expr.gsub('%d', '%f') % [a, op1, b, op2, c, op3, d]
if eval(test) == @@objective
@solutions << expr % [a, op1, b, op2, c, op3, d]
end
end
end
end