]> gitweb.factorcode.org Git - factor.git/blob - extra/project-euler/042/042.factor
project-euler: Rewrap, update links, add copyrights, tests
[factor.git] / extra / project-euler / 042 / 042.factor
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 ;
5 IN: project-euler.042
6
7 ! https://projecteuler.net/problem=42
8
9 ! DESCRIPTION
10 ! -----------
11
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:
14
15 !     1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
16
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.
22
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?
26
27
28 ! SOLUTION
29 ! --------
30
31 <PRIVATE
32
33 : source-042 ( -- seq )
34     "resource:extra/project-euler/042/words.txt"
35     ascii file-contents [ quotable? ] filter "," split ;
36
37 : (triangle-upto) ( limit n -- )
38     2dup nth-triangle > [
39         dup nth-triangle , 1 + (triangle-upto)
40     ] [
41         2drop
42     ] if ;
43
44 : triangle-upto ( n -- seq )
45     [ 1 (triangle-upto) ] { } make ;
46
47 PRIVATE>
48
49 : euler042 ( -- answer )
50     source-042 [ alpha-value ] map dup supremum
51     triangle-upto [ member? ] curry count ;
52
53 ! [ euler042 ] 100 ave-time
54 ! 19 ms ave run time - 1.97 SD (100 trials)
55
56
57 ! ALTERNATE SOLUTIONS
58 ! -------------------
59
60 ! Use the inverse function of n * (n + 1) / 2 and test if the result is an integer
61
62 <PRIVATE
63
64 : triangle? ( n -- ? )
65     8 * 1 + sqrt 1 - 2 / 1 mod zero? ;
66
67 PRIVATE>
68
69 : euler042a ( -- answer )
70     source-042 [ alpha-value ] map [ triangle? ] count ;
71
72 ! [ euler042a ] 100 ave-time
73 ! 21 ms ave run time - 2.2 SD (100 trials)
74
75 SOLUTION: euler042a