1 ! Copyright (c) 2008 Aaron Schaefer.
2 ! See https://factorcode.org/license.txt for BSD license.
3 USING: kernel math math.combinatorics math.functions math.parser
4 ranges project-euler.common sequences sets ;
7 ! https://projecteuler.net/problem=32
12 ! The product 7254 is unusual, as the identity, 39 × 186 = 7254,
13 ! containing multiplicand, multiplier, and product is 1 through
16 ! Find the sum of all products whose
17 ! multiplicand/multiplier/product identity can be written as a 1
18 ! through 9 pandigital.
20 ! HINT: Some products can be obtained in more than one way so be
21 ! sure to only include it once in your sum.
27 ! Generate all pandigital numbers and then check if they fit the
32 : source-032 ( -- seq )
34 9 <iota> permutation [ 1 + ] map digits>number
38 number>string 1 cut-slice 4 cut-slice
39 [ string>number ] tri@ [ * ] dip = ;
42 number>string 2 cut-slice 3 cut-slice
43 [ string>number ] tri@ [ * ] dip = ;
46 [ 1and4 ] [ 2and3 ] bi or ;
48 : products ( seq -- m )
53 : euler032 ( -- answer )
54 source-032 [ valid? ] filter products members sum ;
56 ! [ euler032 ] 10 ave-time
57 ! 16361 ms ave run time - 417.8 SD (10 trials)
63 ! Generate all reasonable multiplicand/multiplier pairs, then multiply and see
64 ! if the equation is pandigital
68 ! multiplicand/multiplier/product
70 2dup * [ number>string ] tri@ 3append string>number ;
74 : euler032a ( -- answer )
76 [ mmp ] cartesian-map concat
77 [ pandigital? ] filter
78 products members sum ;
80 ! [ euler032a ] 10 ave-time
81 ! 2624 ms ave run time - 131.91 SD (10 trials)