Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
覆面算(汎用版)
# 問題:
# 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
You can’t perform that action at this time.