JavaScript Implementation of Problem 22

View source code here on GitHub!

Includes

Problem Solution

p0022()

Project Euler Problem 22

Problem:

Using names.txt (right click and 'Save Link/Target As...'), 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.

What is the total of all the name scores in the file?

Returns:

number --

 1/**
 2 * Project Euler Problem 22
 3 *
 4 *
 5 * Problem:
 6 *
 7 * Using names.txt (right click and 'Save Link/Target As...'), a 46K text file
 8 * containing over five-thousand first names, begin by sorting it into
 9 * alphabetical order. Then working out the alphabetical value for each name,
10 * multiply this value by its alphabetical position in the list to obtain a name
11 * score.
12 *
13 * For example, when the list is sorted into alphabetical order, COLIN, which is
14 * worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would
15 * obtain a score of 938 × 53 = 49714.
16 *
17 * What is the total of all the name scores in the file?
18 *
19 * @return {number}
20 */
21exports.p0022 = function() {
22    const contents = require('./lib/utils.js').get_data_file('p0022_names.txt');
23    const names = contents.split('"').join('').split(',');
24    names.sort();
25    let sum = 0;
26    for (let i = 0; i < names.length; i += 1) {
27        let quantity = 0;
28        for (let j = 0; j < names[i].length; j += 1) {
29            quantity += names[i].charCodeAt(j) & 0x3F;
30        }
31        sum += quantity * (i + 1);
32    }
33    return sum;
34};

Tags: word-problem, sorting, file-io