|
| 1 | +# Pandigital products |
| 2 | +# Problem 32 |
| 3 | +# We shall say that an n-digit number is pandigital if it makes use of all the |
| 4 | +# digits 1 to n exactly once; for example, |
| 5 | +# the 5-digit number, 15234, is 1 through 5 pandigital. |
| 6 | + |
| 7 | +# The product 7254 is unusual, as the identity, 39 × 186 = 7254, |
| 8 | +# containing multiplicand, multiplier, and product is 1 through 9 pandigital. |
| 9 | + |
| 10 | +# Find the sum of all products whose multiplicand/multiplier/product identity |
| 11 | +# can be written as a 1 through 9 pandigital. |
| 12 | + |
| 13 | +# HINT: Some products can be obtained in more than one way so be sure to only |
| 14 | +# include it once in your sum. |
| 15 | + |
| 16 | +# Solution by Sam Gerber |
| 17 | + |
| 18 | +# This method blah |
| 19 | +def pandigital_products |
| 20 | + characters = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0] |
| 21 | + equations = characters.permutation.sort.uniq |
| 22 | + results = [] |
| 23 | + |
| 24 | + equations.each do |equation| |
| 25 | + star_index = equation.index(0) |
| 26 | + break unless star_index > 0 && star_index < 5 |
| 27 | + number1 = equation[0...star_index].join.to_i |
| 28 | + equation = equation[star_index + 1..-1] |
| 29 | + equal_index = equation.index(0) |
| 30 | + break unless equal_index > 0 && equal_index < equation.length - 1 |
| 31 | + number2 = equation[0...equal_index].join.to_i |
| 32 | + product = equation[equal_index + 1..-1].join.to_i |
| 33 | + results << [number1, number2, product] if number1 * number2 == product |
| 34 | + end |
| 35 | + |
| 36 | + results |
| 37 | +end |
| 38 | + |
| 39 | + |
| 40 | + |
| 41 | + |
| 42 | + |
| 43 | +# This method returns true if the numbers contain all the |
| 44 | +# digits from 1 to n |
| 45 | +def is_pandigital?(*numbers, n) |
| 46 | + numbers = numbers.join.split("").sort |
| 47 | + numbers.count == numbers.uniq.count && numbers.first == "1" && numbers.last == n.to_s |
| 48 | +end |
| 49 | + |
| 50 | +print pandigital_products |
0 commit comments