1 ! Copyright (c) 2008 Aaron Schaefer.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: kernel math math.combinatorics math.functions math.parser math.ranges
4 project-euler.common sequences sets ;
7 ! http://projecteuler.net/index.php?section=problems&id=32
12 ! The product 7254 is unusual, as the identity, 39 × 186 = 7254, containing
13 ! multiplicand, multiplier, and product is 1 through 9 pandigital.
15 ! Find the sum of all products whose multiplicand/multiplier/product identity
16 ! can be written as a 1 through 9 pandigital.
18 ! HINT: Some products can be obtained in more than one way so be sure to only
19 ! include it once in your sum.
25 ! Generate all pandigital numbers and then check if they fit the identity
29 : source-032 ( -- seq )
30 9 factorial [ 9 permutation [ 1+ ] map 10 digits>integer ] map ;
33 number>string 1 cut-slice 4 cut-slice
34 [ string>number ] tri@ [ * ] dip = ;
37 number>string 2 cut-slice 3 cut-slice
38 [ string>number ] tri@ [ * ] dip = ;
41 [ 1and4 ] [ 2and3 ] bi or ;
43 : products ( seq -- m )
48 : euler032 ( -- answer )
49 source-032 [ valid? ] filter products prune sum ;
51 ! [ euler032 ] 10 ave-time
52 ! 16361 ms ave run time - 417.8 SD (10 trials)
58 ! Generate all reasonable multiplicand/multiplier pairs, then multiply and see
59 ! if the equation is pandigital
63 : source-032a ( -- seq )
64 50 [1,b] 2000 [1,b] cartesian-product ;
66 ! multiplicand/multiplier/product
68 first2 2dup * [ number>string ] tri@ 3append string>number ;
72 : euler032a ( -- answer )
73 source-032a [ mmp ] map [ pandigital? ] filter products prune sum ;
75 ! [ euler032a ] 10 ave-time
76 ! 2624 ms ave run time - 131.91 SD (10 trials)