]> gitweb.factorcode.org Git - factor.git/blob - extra/project-euler/150/150.factor
Delete empty unit tests files, remove 1- and 1+, reorder IN: lines in a lot of places...
[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: hints kernel locals math math.order math.ranges project-euler.common
4     sequences sequences.private ;
5 IN: project-euler.150
6
7 ! http://projecteuler.net/index.php?section=problems&id=150
8
9 ! DESCRIPTION
10 ! -----------
11
12 ! In a triangular array of positive and negative integers, we wish to find a
13 ! sub-triangle such that the sum of the numbers it contains is the smallest
14 ! possible.
15
16 ! In the example below, it can be easily verified that the marked triangle
17 ! satisfies this condition having a sum of -42.
18
19 ! We wish to make such a triangular array with one thousand rows, so we
20 ! generate 500500 pseudo-random numbers sk in the range +/-2^19, using a type of
21 ! random number generator (known as a Linear Congruential Generator) as
22 ! follows:
23
24 ! ...
25
26 ! Find the smallest possible sub-triangle sum.
27
28
29 ! SOLUTION
30 ! --------
31
32 <PRIVATE
33
34 ! sequence helper functions
35
36 : partial-sums ( seq -- sums )
37     0 [ + ] accumulate swap suffix ; inline
38
39 : (partial-sum-infimum) ( inf sum elt -- inf sum )
40     + [ min ] keep ; inline
41
42 : partial-sum-infimum ( seq -- seq )
43     0 0 rot [ (partial-sum-infimum) ] each drop ; inline
44
45 : map-infimum ( seq quot -- min )
46     [ min ] compose 0 swap reduce ; inline
47
48 ! triangle generator functions
49
50 : next ( t -- new-t s )
51     615949 * 797807 + 20 2^ rem dup 19 2^ - ; inline
52
53 : sums-triangle ( -- seq )
54     0 1000 [1,b] [ [ next ] replicate partial-sums ] map nip ;
55
56 :: (euler150) ( m -- n )
57     [let | table [ sums-triangle ] |
58         m [| x |
59             x 1 + [| y |
60                 m x - [0,b) [| z |
61                     x z + table nth-unsafe
62                     [ y z + 1 + swap nth-unsafe ]
63                     [ y        swap nth-unsafe ] bi -
64                 ] map partial-sum-infimum
65             ] map-infimum
66         ] map-infimum
67     ] ;
68
69 HINTS: (euler150) fixnum ;
70
71 PRIVATE>
72
73 : euler150 ( -- answer )
74     1000 (euler150) ;
75
76 ! [ euler150 ] 10 ave-time
77 ! 30208 ms ave run time - 593.45 SD (10 trials)
78
79 SOLUTION: euler150