Created
November 16, 2018 17:53
-
-
Save mizhi/e45d65e365541a9ef6a117013a572701 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # *=== Friday Nov 16th 2018 - Daily Programmer ===* | |
| # | |
| # *[Name Scores]* | |
| # | |
| # Using the provided `names.txt`, a 46K text file containing over five-thousand | |
| # first names, begin by sorting it into alphabetical order. Then working out the | |
| # alphabetical value for each name, multiply this value by its alphabetical | |
| # position in the list to obtain a name score. | |
| # | |
| # For example, when the list is sorted into alphabetical order, COLIN, which is | |
| # worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN | |
| # would obtain a score of 938 × 53 = 49714. | |
| SCORE_DICT = ("A".."Z").each_with_index.map { |k, v| [k, v.succ] }.to_h | |
| def sorted_names | |
| File.open("names.txt") do |file| | |
| file.read.split(",").sort | |
| end | |
| end | |
| def score_name(name) | |
| name.each_char.reduce(0) { |acc, char| (SCORE_DICT[char] || 0) + acc } | |
| end | |
| puts sorted_names. | |
| each_with_index. | |
| reduce(0) { |acc, (name, index)| acc + score_name(name) * index.succ } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
871198282