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
5 FROM: project-euler.common => permutations? ;
8 ! http://projecteuler.net/index.php?section=problems&id=49
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.
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.
20 ! What 12-digit number do you form by concatenating the three terms in this
29 : collect-permutations ( seq -- seq )
30 [ V{ } clone ] [ dup ] bi* [
31 dupd '[ _ permutations? ] filter
32 [ diff ] keep pick push
35 : potential-sequences ( -- seq )
36 1000 9999 primes-between
37 collect-permutations [ length 3 >= ] filter ;
39 : arithmetic-terms ( m n -- seq )
40 2dup [ swap - ] keep + 3array ;
42 : (find-unusual-terms) ( n seq -- seq/f )
43 [ [ arithmetic-terms ] with map ] keep
44 '[ _ [ last ] dip member? ] find nip ;
46 : find-unusual-terms ( seq -- seq/? )
47 unclip-slice over (find-unusual-terms) [
50 dup length 3 >= [ find-unusual-terms ] [ drop f ] if
53 : 4digit-concat ( seq -- str )
54 0 [ [ 10000 * ] dip + ] reduce ;
58 : euler049 ( -- answer )
59 potential-sequences [ find-unusual-terms ] map sift
60 [ { 1487 4817 8147 } = not ] find nip 4digit-concat ;
62 ! [ euler049 ] 100 ave-time
63 ! 206 ms ave run time - 10.25 SD (100 trials)