]> gitweb.factorcode.org Git - factor.git/blob - extra/project-euler/022/022.factor
b4910e5885fb4ef30c7be01f21f94d38b89a3ed6
[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: io.files kernel math math.parser namespaces sequences sorting splitting
4     strings system vocabs ;
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     "extra/project-euler/022/names.txt" resource-path
32     file-contents [ quotable? ] subset "," split ;
33
34 : alpha-value ( str -- n )
35     [ string>digits sum ] keep length 9 * - ;
36
37 : name-scores ( seq -- seq )
38     dup length [ 1+ swap alpha-value * ] 2map ;
39
40 PRIVATE>
41
42 : euler022 ( -- answer )
43     source-022 natural-sort name-scores sum ;
44
45 ! [ euler022 ] 100 ave-time
46 ! 59 ms run / 1 ms GC ave time - 100 trials
47
48 ! source-022 [ natural-sort name-scores sum ] curry 100 ave-time
49 ! 45 ms run / 1 ms GC ave time - 100 trials
50
51 MAIN: euler022