Skip to content

Commit 552cca4

Browse files
committed
Resolve Project Euler 22
1 parent d94929e commit 552cca4

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

Project-Euler/Problem022.js

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/**
2+
* Problem 22 - Names scores
3+
* @see {@link https://projecteuler.net/problem=22}
4+
*
5+
* Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over
6+
* five-thousand first names, begin by sorting it into alphabetical order. Then working out the
7+
* alphabetical value for each name, multiply this value by its alphabetical position in the list to
8+
* obtain a name score.
9+
*
10+
* For example, when the list is sorted into alphabetical order, COLIN,
11+
* which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list.
12+
* So, COLIN would obtain a score of 938 × 53 = 49714.
13+
*
14+
* What is the total of all the name scores in the file?
15+
*/
16+
17+
export function namesScores (namesTxt) {
18+
namesTxt = namesTxt.replaceAll('"', '')
19+
const names = namesTxt.split(',')
20+
21+
names.sort((a, b) => (a > b) - (a < b))
22+
23+
let totalSum = 0
24+
for (let i = 0; i < names.length; i++) {
25+
let nameSum = 0
26+
for (let j = names[i].length; j--;) {
27+
nameSum += names[i].charCodeAt(j) - 64
28+
}
29+
30+
totalSum += nameSum * (i + 1)
31+
}
32+
33+
return totalSum
34+
}

0 commit comments

Comments
 (0)