とんちゃんといっしょ

Cloudに関する技術とか日常とかについて書いたり書かなかったり

久しぶりRubyでProject Eulerをやってみた

最近Rubyをまともに使った覚えが無いので、
1年ぶりぐらいになるかもしれないけどProject Eulerをやってみることに。


今回は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.

http://projecteuler.net/index.php?section=problems&id=32

1-9までの9桁を掛け算の結果で出したい場合、
9つの数字を表示可能な計算は以下の2通りしかない。

  • 1000 * 1 = 1000
  • 100 * 10 = 1000

この2通りに関して1-9の配列から値の組み合わせでいけるか、
調べて計算をすればいけるはず。


そしてソースコードはこちら

array = [*1..9]
ans = []

(1..2).each do |i|
  array.permutation(i).each do |multiplicand|
    (array - multiplicand).permutation(5-i).each do |multiplier|
       result = multiplicand.join.to_i * multiplier.join.to_i
       ans_array = array - multiplicand - multiplier
       if result.size == 4
         ans_array.permutation.each do |e|
           ans << result if e.join.to_i == result
         end
       end
    end
  end
end

puts ans.uniq.inject(:+)

結論
Array::permutationが強すぎる。