Created
May 3, 2020 07:13
-
-
Save tsaito-cyber/409060a204122f6286b3935ab376e7a6 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
# 問題: | |
# http://hidesugar.web.fc2.com/ym2/ym2musikuizan2.txt | |
# ABCDEF * G = FABCDE | |
# 解答: 230769 * 4 = 923076 | |
def solve(sx, sy, sz, mapping) | |
x = sx.inject(0) {|sum, x| sum * 10 + mapping[x]} | |
y = sy.inject(0) {|sum, y| sum * 10 + mapping[y]} | |
z = Enumerator.new do |e| | |
t = (x * y) | |
loop do | |
e << [t % 10, t, (t = t/10)] | |
end | |
end.take_while {|t| t[1] != 0}.map(&:first) | |
used = mapping.values.map {|k| [k, true]}.to_h | |
result = sz.reverse.map.with_index do |c, index| | |
digit = z[index] | |
if mapping.has_key?(c) | |
mapping[c] === digit && used[digit] | |
else | |
next false if used.has_key?(digit) | |
mapping[c] = digit | |
used[digit] = true | |
end | |
end | |
result.all? ? [x, y, z, mapping] : nil | |
end | |
def explore(sx, sy, sz) | |
sx = sx.chars | |
sy = sy.chars | |
sz = sz.chars | |
vals = (sx + sy).uniq | |
(0..9).to_a.permutation(vals.size) do |nums| | |
fail if vals.size != nums.size | |
if (res = solve(sx, sy, sz, vals.zip(nums).to_h)) | |
x, y, z, mapping = res | |
puts "#{x} * #{y} = #{x * y}" | |
end | |
end | |
end | |
# explore('vivid', 'vive', 'brillante') | |
explore('ABCDEF', 'G', 'FABCDE') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment