12345678910111213141516171819202122232425262728293031323334353637383940414243444546 |
- #!/usr/bin/ruby
- # Author: Daniel "Trizen" Șuteu
- # License: GPLv3
- # Website: https://github.com/trizen
- # Find the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 pandigital.
- # https://projecteuler.net/problem=32
- # Runtime: 4.574s (previously: 7.707s)
- func valid_num(n) {
- var digits = n.digits
- return false if (digits.contains(0))
- return false if (digits.uniq.len != n.len)
- return true
- }
- var a = (range(1, 99) -> grep(valid_num))
- var b = (range(1, 9999) -> grep(valid_num))
- var sum = 0
- var seen = Hash()
- a.each { |x|
- b.each { |y|
- var prod = x*y
- var pd = ("%s%s%s" % (x, y, prod))
- pd.len == 9 || next
- valid_num(prod) || next
- valid_num(Num(pd)) || next
- next if seen.has(prod)
- seen{prod} = 1
- say "#{x} * #{y} = #{prod}"
- sum += prod
- }
- }
- say sum
|