Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@takuma-saito
Last active May 3, 2020 06:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save takuma-saito/995ee55eba353a64ca71dd577a00fd4e to your computer and use it in GitHub Desktop.
Save takuma-saito/995ee55eba353a64ca71dd577a00fd4e to your computer and use it in GitHub Desktop.
fukumen.rb
# 問題: https://twitter.com/nada_mathclub/status/1256418924737880069
# : vivid * vive = brillante の覆面算を解く
# 解答: 62621 * 6267 = 392445807
def solve(v, i, d, e)
return nil if v == 0
vivid = [v, i, v, i, d].inject(0) {|sum, x| sum * 10 + x}
vive = [v, i, v, e].inject(0) {|sum, x| sum * 10 + x}
brillante = Enumerator.new do |e|
t = (vivid * vive)
loop do
e << [t % 10, t, (t = t/10)]
end
end.take_while {|t| t[1] != 0}.map(&:first)
return nil if brillante.size < 9
used = {v => true, i => true, d => true, e => true}
mapping = {'v' => v, 'i' => i, 'd' => d, 'e' => e}
result = 'brillante'.chars.reverse.map.with_index do |c, index|
digit = brillante[index]
if mapping.has_key?(c)
mapping[c] === digit
else
next false if used.has_key?(digit) || (index === 8 && digit == 0)
mapping[c] = digit
used[digit] = true
end
end
result.all? ? [vivid, vive, vivid * vive] : nil
end
(0..9).to_a.permutation(4) do |nums|
if (res = solve(*nums))
vivid, vive, brillante = res
puts "#{vivid} * #{vive} = #{vivid * vive}"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment