1 ! Copyright (c) 2008 Aaron Schaefer.
2 ! See https://factorcode.org/license.txt for BSD license.
3 USING: ascii io.encodings.ascii io.files kernel make math
4 math.functions project-euler.common sequences splitting ;
7 ! https://projecteuler.net/problem=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
18 ! to its alphabetical position and adding these values we form a
19 ! word value. For example, the word value for SKY is 19 + 11 +
20 ! 25 = 55 = t10. If the word value is a triangle number then we
21 ! shall call the word a triangle word.
23 ! Using words.txt (right click and 'Save Link/Target As...'), a
24 ! 16K text file containing nearly two-thousand common English
25 ! words, how many are triangle words?
33 : source-042 ( -- seq )
34 "resource:extra/project-euler/042/words.txt"
35 ascii file-contents [ quotable? ] filter "," split ;
37 : (triangle-upto) ( limit n -- )
39 dup nth-triangle , 1 + (triangle-upto)
44 : triangle-upto ( n -- seq )
45 [ 1 (triangle-upto) ] { } make ;
49 : euler042 ( -- answer )
50 source-042 [ alpha-value ] map dup maximum
51 triangle-upto [ member? ] curry count ;
53 ! [ euler042 ] 100 ave-time
54 ! 19 ms ave run time - 1.97 SD (100 trials)
60 ! Use the inverse function of n * (n + 1) / 2 and test if the result is an integer
64 : triangle? ( n -- ? )
65 8 * 1 + sqrt 1 - 2 / 1 mod zero? ;
69 : euler042a ( -- answer )
70 source-042 [ alpha-value ] map [ triangle? ] count ;
72 ! [ euler042a ] 100 ave-time
73 ! 21 ms ave run time - 2.2 SD (100 trials)