Created
May 3, 2016 21:39
-
-
Save pcarrier/81f89f9172d0af35e965b4e0e48cc7ea to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
OPS = [:+, :-, :*, :/] | |
ALL_OPS = OPS.product(OPS).product(OPS).map do |n| n.flatten end | |
ALL_FOUR_CARDS = (0..9999).map do |n| | |
a = n % 10 + 1 | |
b = n/10 % 10 + 1 | |
c = n/100 % 10 + 1 | |
d = n/1000 % 10 + 1 | |
[a,b,c,d].sort | |
end | |
UNIQUE_FOUR_CARDS = ALL_FOUR_CARDS.uniq | |
def findsol cards | |
cards.permutation.each do |cards| | |
a, b, c, d = *cards | |
ALL_OPS.each do |o1, o2, o3| | |
begin | |
x = a.to_f.send(o1, b) | |
y = c.to_f.send(o2, d) | |
z = x.send(o3, y) | |
return "(#{o3}(#{o1}#{a} #{b})(#{o2} #{c} #{d}))" if z == 24 | |
rescue ZeroDivisionError | |
end | |
end | |
end | |
nil | |
end | |
def repr card | |
sprintf '%2d', card | |
end | |
ALL_FOUR_CARDS.each do |cards| | |
sol = findsol cards | |
r = cards.map { |c| repr c }.join ', ' | |
if sol | |
puts "#{r}: #{sol}" | |
else | |
puts "#{r}: nothing" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment