Created
December 13, 2014 13:49
-
-
Save katoy/2dfd7d41b342ddb70aaf to your computer and use it in GitHub Desktop.
覆面算を ruby で解く。
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
# encoding: utf-8 | |
# See http://web-salad.hateblo.jp/entry/2014/04/06/164312 | |
# このコードを元に、少し変更して、全解を得るようにした。 | |
# 文字に日本語もあつかえるようにした。 | |
# | |
# 覆面算の例: http://ja.wikipedia.org/wiki/%E8%A6%86%E9%9D%A2%E7%AE%97 | |
# | |
DOCUMENT = <<EOS | |
Find solutions to alphametic equations. | |
> Alphametics.solve('SEND + MORE == MONEY') | |
9567 + 1085 == 10652 | |
> Alphametics.solve('AB + 12 = 99') | |
87 + 12 == 99 | |
> Alphametics.solve('twelve + twenty == answer') | |
407927 + 407146 == 815073 | |
> Alphametics.solve('ABCDEF * C == CDEFAB') | |
142857 * 2 == 285714 | |
> Alphametics.solve('kore * are == iroiro') | |
5943 * 143 == 849849 | |
> Alphametics.solve('a + b + c = ab && b + b + b = c') | |
1 + 3 + 9 == 13 && 3 + 3 + 3 == 9 | |
> Alphametics.solve('みず * みず = 飲みみず') | |
76 * 76 == 5776 | |
EOS | |
module Alphametics | |
def solve(puzzle) | |
ans = [] | |
words = puzzle.upcase.split(/[ \=\+\-\*\\^<\>\&\|0-9]+/) | |
unique_characters = words.join.split('').uniq | |
fail 'Too many letters' if unique_characters.size >= 11 || unique_characters.size == 0 | |
first_letters = words.map{ |word| word.slice(0) }.uniq | |
n = first_letters.size | |
characters = (first_letters + (unique_characters - first_letters)).join | |
solution = (0..9).to_a.permutation(characters.length) do |guess| | |
next if guess.slice(0, n).include?(0) | |
equation = puzzle.tr(characters, guess.join) | |
ans << equation if eval(equation) | |
end | |
solution if solution.instance_of?(String) | |
ans | |
end | |
module_function :solve | |
end | |
if $PROGRAM_NAME == __FILE__ | |
puts DOCUMENT and return if ARGV.size.zero? | |
ARGV.each do |puzzle| | |
puts puzzle | |
puzzle = puzzle.gsub('=', '==') unless puzzle.index('==') | |
solution = Alphametics.solve(puzzle.upcase) | |
puts solution.join("\n") unless solution.nil? | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment