1 ! Copyright (c) 2007 Aaron Schaefer.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: combinators.lib io io.files kernel math math.parser namespaces sequences
4 sorting splitting strings system vocabs ;
7 ! http://projecteuler.net/index.php?section=problems&id=22
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
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.
22 ! What is the total of all the name scores in the file?
30 : source-022 ( -- seq )
31 "extra/project-euler/022/names.txt" resource-path
32 file-contents [ quotable? ] subset "," split ;
34 : alpha-value ( str -- n )
35 string>digits [ 9 - ] sigma ;
37 : name-scores ( seq -- seq )
38 dup length [ 1+ swap alpha-value * ] 2map ;
42 : euler022 ( -- answer )
43 source-022 natural-sort name-scores sum ;
45 ! [ euler022 ] 100 ave-time
46 ! 59 ms run / 1 ms GC ave time - 100 trials
48 ! source-022 [ natural-sort name-scores sum ] curry 100 ave-time
49 ! 45 ms run / 1 ms GC ave time - 100 trials