]> gitweb.factorcode.org Git - factor.git/blob - extra/project-euler/049/049.factor
factor: trim using lists
[factor.git] / extra / project-euler / 049 / 049.factor
1 ! Copyright (c) 2009 Aaron Schaefer.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: arrays kernel math math.primes project-euler.common
4 sequences sets ;
5 FROM: project-euler.common => permutations? ;
6 IN: project-euler.049
7
8 ! http://projecteuler.net/index.php?section=problems&id=49
9
10 ! DESCRIPTION
11 ! -----------
12
13 ! The arithmetic sequence, 1487, 4817, 8147, in which each of the terms
14 ! increases by 3330, is unusual in two ways: (i) each of the three terms are
15 ! prime, and, (ii) each of the 4-digit numbers are permutations of one another.
16
17 ! There are no arithmetic sequences made up of three 1-, 2-, or 3-digit primes,
18 ! exhibiting this property, but there is one other 4-digit increasing sequence.
19
20 ! What 12-digit number do you form by concatenating the three terms in this
21 ! sequence?
22
23
24 ! SOLUTION
25 ! --------
26
27 <PRIVATE
28
29 : collect-permutations ( seq -- seq )
30     [ V{ } clone ] [ dup ] bi* [
31         dupd '[ _ permutations? ] filter
32         [ diff ] keep pick push
33     ] each drop ;
34
35 : potential-sequences ( -- seq )
36     1000 9999 primes-between
37     collect-permutations [ length 3 >= ] filter ;
38
39 : arithmetic-terms ( m n -- seq )
40     2dup [ swap - ] keep + 3array ;
41
42 : (find-unusual-terms) ( n seq -- seq/f )
43     [ [ arithmetic-terms ] with map ] keep
44     '[ _ [ last ] dip member? ] find nip ;
45
46 : find-unusual-terms ( seq -- seq/? )
47     unclip-slice over (find-unusual-terms) [
48         nip
49     ] [
50         dup length 3 >= [ find-unusual-terms ] [ drop f ] if
51     ] if* ;
52
53 : 4digit-concat ( seq -- str )
54     0 [ [ 10000 * ] dip + ] reduce ;
55
56 PRIVATE>
57
58 : euler049 ( -- answer )
59     potential-sequences [ find-unusual-terms ] map sift
60     [ { 1487 4817 8147 } = not ] find nip 4digit-concat ;
61
62 ! [ euler049 ] 100 ave-time
63 ! 206 ms ave run time - 10.25 SD (100 trials)
64
65 SOLUTION: euler049