Skip to content

Instantly share code, notes, and snippets.

@NotFounds
Last active October 25, 2017 11:38
Show Gist options
  • Save NotFounds/a7151c5e35132f41585397c3a60cdf77 to your computer and use it in GitHub Desktop.
Save NotFounds/a7151c5e35132f41585397c3a60cdf77 to your computer and use it in GitHub Desktop.
Result = Struct.new(:charactor, :expression, :answer)
def to_int(map, str)
str.split(//).reduce(0) {|acc, c| acc * 10 + map[c]}
end
def alphametic(expression)
# count uniq charactors
charactors = Array.new(expression).join.split(//).uniq
length = charactors.length
ret = []
# p = gperm((0..9).to_a, length)
# for ary in p
(0..9).to_a.permutation(length) do |ary|
hash = Hash.new()
for i in 0..(length-1)
hash[charactors[i]] = ary[i]
end
# Most significant digit is non-zero
nonZero = expression.all?{|exp| hash[exp[0]] != 0}
if nonZero
tmp = expression.reduce([]) {|acc, i| acc.push to_int(hash, i)}
ans = tmp.pop
calc = tmp.reduce(0) {|acc, i| acc + i}
if (calc == ans)
ret.push(Result.new(hash), tmp, ans)
end
end
end
ret
end
puts alphametic(["SEND", "MORE", "MONEY"])
#puts alphametic(["すももと", "ももとは", "ともだちだ"])
#puts alphametic(["オオ", "オオ", "カカオ", "オカカ"])
#puts alphametic(["EARTH", "AIR", "FIRE", "WATER", "NATURE"])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment