]> gitweb.factorcode.org Git - factor.git/blob - extra/project-euler/032/032.factor
Factor source files should not be executable
[factor.git] / extra / project-euler / 032 / 032.factor
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 ;
5 IN: project-euler.032
6
7 ! http://projecteuler.net/index.php?section=problems&id=32
8
9 ! DESCRIPTION
10 ! -----------
11
12 ! The product 7254 is unusual, as the identity, 39 × 186 = 7254, containing
13 ! multiplicand, multiplier, and product is 1 through 9 pandigital.
14
15 ! Find the sum of all products whose multiplicand/multiplier/product identity
16 ! can be written as a 1 through 9 pandigital.
17
18 ! HINT: Some products can be obtained in more than one way so be sure to only
19 ! include it once in your sum.
20
21
22 ! SOLUTION
23 ! --------
24
25 ! Generate all pandigital numbers and then check if they fit the identity
26
27 <PRIVATE
28
29 : source-032 ( -- seq )
30     9 factorial iota [
31         9 permutation [ 1 + ] map 10 digits>integer
32     ] map ;
33
34 : 1and4 ( n -- ? )
35     number>string 1 cut-slice 4 cut-slice
36     [ string>number ] tri@ [ * ] dip = ;
37
38 : 2and3 ( n -- ? )
39     number>string 2 cut-slice 3 cut-slice
40     [ string>number ] tri@ [ * ] dip = ;
41
42 : valid? ( n -- ? )
43     [ 1and4 ] [ 2and3 ] bi or ;
44
45 : products ( seq -- m )
46     [ 10 4 ^ mod ] map ;
47
48 PRIVATE>
49
50 : euler032 ( -- answer )
51     source-032 [ valid? ] filter products prune sum ;
52
53 ! [ euler032 ] 10 ave-time
54 ! 16361 ms ave run time - 417.8 SD (10 trials)
55
56
57 ! ALTERNATE SOLUTIONS
58 ! -------------------
59
60 ! Generate all reasonable multiplicand/multiplier pairs, then multiply and see
61 ! if the equation is pandigital
62
63 <PRIVATE
64
65 : source-032a ( -- seq )
66     50 [1,b] 2000 [1,b] cartesian-product ;
67
68 ! multiplicand/multiplier/product
69 : mmp ( pair -- n )
70     first2 2dup * [ number>string ] tri@ 3append string>number ;
71
72 PRIVATE>
73
74 : euler032a ( -- answer )
75     source-032a [ mmp ] map [ pandigital? ] filter products prune sum ;
76
77 ! [ euler032a ] 10 ave-time
78 ! 2624 ms ave run time - 131.91 SD (10 trials)
79
80 SOLUTION: euler032a