]> gitweb.factorcode.org Git - factor.git/blob - extra/project-euler/022/022.factor
project-euler: Rewrap, update links, add copyrights, tests
[factor.git] / extra / project-euler / 022 / 022.factor
1 ! Copyright (c) 2007 Aaron Schaefer.
2 ! See https://factorcode.org/license.txt for BSD license.
3 USING: ascii io.encodings.ascii io.files kernel math
4 project-euler.common sequences sorting splitting ;
5 IN: project-euler.022
6
7 ! https://projecteuler.net/problem=22
8
9 ! DESCRIPTION
10 ! -----------
11
12 ! Using names.txt (right click and 'Save Link/Target As...'), a
13 ! 46K text file containing over five-thousand first names, begin
14 ! by sorting it into alphabetical order. Then working out the
15 ! alphabetical value for each name, multiply this value by its
16 ! alphabetical position in the list to obtain a name score.
17
18 ! For example, when the list is sorted into alphabetical order,
19 ! COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th
20 ! name in the list. So, COLIN would obtain a score of 938 * 53 =
21 ! 49714.
22
23 ! What is the total of all the name scores in the file?
24
25
26 ! SOLUTION
27 ! --------
28
29 <PRIVATE
30
31 : source-022 ( -- seq )
32     "resource:extra/project-euler/022/names.txt"
33     ascii file-contents [ quotable? ] filter "," split ;
34
35 : name-scores ( seq -- seq )
36     [ 1 + swap alpha-value * ] map-index ;
37
38 PRIVATE>
39
40 : euler022 ( -- answer )
41     source-022 sort name-scores sum ;
42
43 ! [ euler022 ] 100 ave-time
44 ! 74 ms ave run time - 5.13 SD (100 trials)
45
46 SOLUTION: euler022