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