]> gitweb.factorcode.org Git - factor.git/blob - extra/project-euler/150/150.factor
Merge branch 'master' of http://factorcode.org/git/factor into experimental
[factor.git] / extra / project-euler / 150 / 150.factor
1 ! Copyright (c) 2008 Eric Mertens
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: kernel math math.order sequences sequences.private
4 locals hints ;
5 IN: project-euler.150
6
7 <PRIVATE
8
9 ! sequence helper functions
10
11 : partial-sums ( seq -- sums )
12     0 [ + ] accumulate swap suffix ; inline
13
14 : (partial-sum-infimum) ( inf sum elt -- inf sum )
15     + [ min ] keep ; inline
16
17 : partial-sum-infimum ( seq -- seq )
18     0 0 rot [ (partial-sum-infimum) ] each drop ; inline
19
20 : generate ( n quot -- seq )
21     [ drop ] prepose map ; inline
22
23 : map-infimum ( seq quot -- min )
24     [ min ] compose 0 swap reduce ; inline
25
26
27 ! triangle generator functions
28
29 : next ( t -- new-t s )
30     615949 * 797807 + 20 2^ rem dup 19 2^ - ; inline
31
32 : sums-triangle ( -- seq )
33     0 1000 [ 1+ [ next ] generate partial-sums ] map nip ; 
34
35 PRIVATE>
36
37 :: (euler150) ( m -- n )
38     [let | table [ sums-triangle ] |
39         m [| x |
40             x 1+ [| y |
41                 m x - [| z |
42                     x z + table nth-unsafe
43                     [ y z + 1+ swap nth-unsafe ]
44                     [ y        swap nth-unsafe ] bi -
45                 ] map partial-sum-infimum
46             ] map-infimum
47         ] map-infimum
48     ] ;
49
50 HINTS: (euler150) fixnum ;
51
52 : euler150 ( -- n )
53     1000 (euler150) ;