feat(euler): 22 - names scores

This commit is contained in:
newt 2024-10-09 18:02:44 +01:00
parent 8c5377ca8c
commit 5f9fdcdc3b
3 changed files with 42 additions and 1 deletions

View file

@ -33,7 +33,7 @@ The source code can be found in the [src](src) directory. My thoughts about some
- [x] [19 - Counting Sundays](src/19%20-%20Counting%20Sundays.ts) - [x] [19 - Counting Sundays](src/19%20-%20Counting%20Sundays.ts)
- [x] [20 - Factorial digit sum](src/20%20-%20Factorial%20digit%20sum.ts) - [x] [20 - Factorial digit sum](src/20%20-%20Factorial%20digit%20sum.ts)
- [x] [21 - Amicable numbers](src/21%20-%20Amicable%20numbers.ts) - [x] [21 - Amicable numbers](src/21%20-%20Amicable%20numbers.ts)
- [ ] 22 - Names scores - [x] [22 - Names scores](src/22%20-%20Names%20scores.ts)
- [ ] 23 - Non-abundant sums - [ ] 23 - Non-abundant sums
- [ ] 24 - Lexicographic permutations - [ ] 24 - Lexicographic permutations
- [ ] 25 - 1000-digit Fibonacci number - [ ] 25 - 1000-digit Fibonacci number

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,40 @@
// 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?
export = {};
import fs from 'fs';
import path, { parse } from 'path';
import { resources } from '../constants';
const parseNames = () =>
fs
.readFileSync(path.join(resources, 'p022_names.txt'))
.toString()
.split(',')
.map(name => name.replace(/"/g, '').toLowerCase())
.sort((a, b) => a.localeCompare(b));
const nameScore = (name: string, position: number) => {
let letterSum = 0;
for (let i = 0; i < name.length; i++) {
letterSum += name.charCodeAt(i) - 96; // use char codes to easily find the alphabetical location
}
return letterSum * position;
};
const nameScoreTotal = (names: string[]) => {
let total = 0;
names.forEach((name, i) => {
total += nameScore(name, i + 1);
});
return total;
};
// Output
const names = parseNames();
console.log(nameScoreTotal(names));