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 ;
7 ! http://projecteuler.net/index.php?section=problems&id=150
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
16 ! In the example below, it can be easily verified that the marked triangle
17 ! satisfies this condition having a sum of -42.
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
26 ! Find the smallest possible sub-triangle sum.
34 ! sequence helper functions
36 : partial-sums ( seq -- sums )
37 0 [ + ] accumulate swap suffix ; inline
39 : (partial-sum-infimum) ( inf sum elt -- inf sum )
40 + [ min ] keep ; inline
42 : partial-sum-infimum ( seq -- seq )
43 0 0 rot [ (partial-sum-infimum) ] each drop ; inline
45 : map-infimum ( seq quot -- min )
46 [ min ] compose 0 swap reduce ; inline
48 ! triangle generator functions
50 : next ( t -- new-t s )
51 615949 * 797807 + 20 2^ rem dup 19 2^ - ; inline
53 : sums-triangle ( -- seq )
54 0 1000 [1,b] [ [ next ] replicate partial-sums ] map nip ;
56 :: (euler150) ( m -- n )
57 [let | table [ sums-triangle ] |
61 x z + table nth-unsafe
62 [ y z + 1+ swap nth-unsafe ]
63 [ y swap nth-unsafe ] bi -
64 ] map partial-sum-infimum
69 HINTS: (euler150) fixnum ;
73 : euler150 ( -- answer )
76 ! [ euler150 ] 10 ave-time
77 ! 30208 ms ave run time - 593.45 SD (10 trials)