1 ! Copyright (c) 2008 Aaron Schaefer.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: ascii io.encodings.ascii io.files kernel make math math.functions
4 namespaces project-euler.common sequences splitting ;
7 ! http://projecteuler.net/index.php?section=problems&id=42
12 ! The nth term of the sequence of triangle numbers is given by,
13 ! tn = n * (n + 1) / 2; so the first ten triangle numbers are:
15 ! 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
17 ! By converting each letter in a word to a number corresponding to its
18 ! alphabetical position and adding these values we form a word value. For
19 ! example, the word value for SKY is 19 + 11 + 25 = 55 = t10. If the word value
20 ! is a triangle number then we shall call the word a triangle word.
22 ! Using words.txt (right click and 'Save Link/Target As...'), a 16K text file
23 ! containing nearly two-thousand common English words, how many are triangle
32 : source-042 ( -- seq )
33 "resource:extra/project-euler/042/words.txt"
34 ascii file-contents [ quotable? ] filter "," split ;
36 : (triangle-upto) ( limit n -- )
38 dup nth-triangle , 1+ (triangle-upto)
43 : triangle-upto ( n -- seq )
44 [ 1 (triangle-upto) ] { } make ;
48 : euler042 ( -- answer )
49 source-042 [ alpha-value ] map dup supremum
50 triangle-upto [ member? ] curry count ;
52 ! [ euler042 ] 100 ave-time
53 ! 19 ms ave run time - 1.97 SD (100 trials)
59 ! Use the inverse function of n * (n + 1) / 2 and test if the result is an integer
63 : triangle? ( n -- ? )
64 8 * 1+ sqrt 1- 2 / 1 mod zero? ;
68 : euler042a ( -- answer )
69 source-042 [ alpha-value ] map [ triangle? ] count ;
71 ! [ euler042a ] 100 ave-time
72 ! 21 ms ave run time - 2.2 SD (100 trials)