032 Pandigital products.sf 913 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. #!/usr/bin/ruby
  2. # Author: Daniel "Trizen" Șuteu
  3. # License: GPLv3
  4. # Website: https://github.com/trizen
  5. # Find the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 pandigital.
  6. # https://projecteuler.net/problem=32
  7. # Runtime: 4.574s (previously: 7.707s)
  8. func valid_num(n) {
  9. var digits = n.digits
  10. return false if (digits.contains(0))
  11. return false if (digits.uniq.len != n.len)
  12. return true
  13. }
  14. var a = (range(1, 99) -> grep(valid_num))
  15. var b = (range(1, 9999) -> grep(valid_num))
  16. var sum = 0
  17. var seen = Hash()
  18. a.each { |x|
  19. b.each { |y|
  20. var prod = x*y
  21. var pd = ("%s%s%s" % (x, y, prod))
  22. pd.len == 9 || next
  23. valid_num(prod) || next
  24. valid_num(Num(pd)) || next
  25. next if seen.has(prod)
  26. seen{prod} = 1
  27. say "#{x} * #{y} = #{prod}"
  28. sum += prod
  29. }
  30. }
  31. say sum