Problem 32

Problem 32

We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once; for example, the 5-digit number, 15234, is 1 through 5 pandigital.

The product 7254 is unusual, as the identity, 39 186 = 7254, containing multiplicand, multiplier, and product is 1 through 9 pandigital.

Find the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 pandigital.

HINT: Some products can be obtained in more than one way so be sure to only include it once in your sum.

x = [] [[(1..9), (1000..9999)],[(10..99), (100..999)]].each {|r| r.first.each {|a| r.last.each {|b| c = a*b if c.to_s.size == 4 && ([a, b, c].map{|e| e.to_s.split(//)}.flatten.uniq - ['0']).size == 9 x << c p [a,b,c] end } } } p x.uniq.inject(:+)

poniżej moje podejście

[code=ruby]numery = [1,2,3,4,5,6,7,8,9]
results = []

numery.permutation.to_a.each do |hh|
if hh[0…1].join.to_i * hh[2…4].join.to_i == hh[5…8].join.to_i or hh.at(0).to_i * hh[1…4].join.to_i == hh[5…8].join.to_i
results << hh[5…8].join.to_i
end
end
puts results.uniq.inject(:+)[/code]
co warto zauważyć?;

  • działanie tylko na permutacjach zaoszczędza nam sporo obliczeń
  • możliwe działania to tylko 1C4C=4C lub 2C3C=4C (C=cyfra)