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