]> gitweb.factorcode.org Git - factor.git/blob - extra/project-euler/067/067.factor
factor: trim using lists
[factor.git] / extra / project-euler / 067 / 067.factor
1 ! Copyright (c) 2007 Samuel Tardieu, Aaron Schaefer.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: io.files math.parser project-euler.common
4 io.encodings.ascii sequences splitting ;
5 IN: project-euler.067
6
7 ! http://projecteuler.net/index.php?section=problems&id=67
8
9 ! DESCRIPTION
10 ! -----------
11
12 ! By starting at the top of the triangle below and moving to adjacent numbers
13 ! on the row below, the maximum total from top to bottom is 23.
14
15 !        3
16 !       7 5
17 !      2 4 6
18 !     8 5 9 3
19
20 ! That is, 3 + 7 + 4 + 9 = 23.
21
22 ! Find the maximum total from top to bottom in triangle.txt (right click and
23 ! 'Save Link/Target As...'), a 15K text file containing a triangle with
24 ! one-hundred rows.
25
26 ! NOTE: This is a much more difficult version of Problem 18. It is not possible
27 ! to try every route to solve this problem, as there are 2^99 altogether! If you
28 ! could check one trillion (10^12) routes every second it would take over twenty
29 ! billion years to check them all. There is an efficient algorithm to solve it. ;o)
30
31
32 ! SOLUTION
33 ! --------
34
35 ! Propagate from bottom to top the longest cumulative path as is done in
36 ! problem 18.
37
38 <PRIVATE
39
40 : source-067 ( -- seq )
41     "resource:extra/project-euler/067/triangle.txt"
42     ascii file-lines [ split-words [ string>number ] map ] map ;
43
44 PRIVATE>
45
46 : euler067 ( -- answer )
47     source-067 propagate-all first first ;
48
49 ! [ euler067 ] 100 ave-time
50 ! 20 ms ave run time - 2.12 SD (100 trials)
51
52
53 ! ALTERNATE SOLUTIONS
54 ! -------------------
55
56 : euler067a ( -- answer )
57     source-067 max-path ;
58
59 ! [ euler067a ] 100 ave-time
60 ! 21 ms ave run time - 2.65 SD (100 trials)
61
62 SOLUTION: euler067a