Skip to content

Instantly share code, notes, and snippets.

@selman
Created October 24, 2011 13:16
Show Gist options
  • Save selman/1309005 to your computer and use it in GitHub Desktop.
Save selman/1309005 to your computer and use it in GitHub Desktop.
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