Anonymous user
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
EXPRESSIONS = [
'((%
'(%
'(%
'%
'%
]▼
OPERATORS = [:+, :-, :*, :/].repeated_permutation(3).to_a
def self.solve(digits)
solutions = []
perms = digits.permutation.to_a.uniq
# evaluate using rational arithmetic
text = expr %
solutions << text.delete("r") if value == 24
▲ value = eval(test) rescue -1 # catch division by zero
end
solutions
Line 4,987 ⟶ 4,981:
digits.size == 4 or raise "error: need 4 digits, only have #{digits.size}"
solutions =
if solutions.empty?
puts "no solutions"
Line 4,996 ⟶ 4,990:
{{out}}
<pre>$ ruby
no solutions
$ ruby
found 8 solutions, including (1 + 2) * (1 + 7)
(1 + 2) * (1 + 7)
Line 5,010 ⟶ 5,004:
(7 + 1) * (2 + 1)
$ ruby
found 12 solutions, including (8 / 2) * (9 - 3)
((9 - 3) * 8) / 2
|