Created
October 24, 2011 13:16
-
-
Save selman/1309005 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
require 'set' | |
DIGITS = ('0'..'9').to_a | |
def solve alphametics | |
firsts, rests = Set.new, Set.new | |
alphametics.scan(/\w+/) do |w| | |
firsts << w[0] | |
rests += w[1..-1].chars | |
end | |
chars = firsts + rests | |
fail "chars.size > 10" if chars.size > 10 | |
size = firsts.size | |
DIGITS.permutation(chars.size).each do |p| | |
begin | |
am = alphametics.dup | |
chars.zip(p).each {|s, d| am.tr!(s, d)} | |
return am if eval(am) | |
end unless p[0..size].include?('0') | |
end | |
fail "unsolvable: #{alphametics}" | |
end | |
puts solve("mad * man == asylum") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment