Names Scores
Using 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 \times 53 = 49714\).
What is the total of all the name scores in the file?
Solution
It’s a rather easy problem due to a small dataset. No need to use any tricks to solve it.
When processing the names we need to remove the quotation marks that appear as the first and the last character:
name => name.slice(1, name.length - 1)
Here’s the complete solution:
object Euler022 extends EulerApp {
override def execute(): Any =
loadFileAsLines()
.flatMap(_.split(","))
.view
.map(name => name.slice(1, name.length - 1))
.sorted
.zipWithIndex
.map { case (name, index) =>
name.map(c => (c - 'A') + 1).sum * (index + 1)
}
.sum
}
The score calculating part might look a bit enigmatic, so I’ll give a couple words of explanation:
.zipWithIndex
.map { case (name, index) =>
name.map(c => (c - 'A') + 1).sum * (index + 1)
}
The c here is a character, like A, and if we remove A from it then we get 0. So we need to add 1 to it, since A
is the first letter of the alphabet. Once we get this score, it needs to be multiplied by (index + 1) because the name
indices start from 0. Score of the first name needs to be multiplied by 1, not 0.