Last active
November 5, 2016 20:09
-
-
Save nerdybeast/1d87018901e0de495c0895d72f31dd18 to your computer and use it in GitHub Desktop.
Euler 22 - Names Scores
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
'use strict'; | |
const fs = require('fs'); | |
const Score = require('./lib/score'); | |
fs.readFile('./names.txt', 'utf8', (err, data) => { | |
if (err) throw err; | |
data = data.replace(/"/g, '').toUpperCase().split(',').sort(); | |
let score = new Score(data); | |
let scoreList = data.map(name => score.getScore(name)); | |
let total = scoreList.reduce((prev, curr) => prev + curr); | |
console.log(`Names Scores Total: ${total}`); | |
}); |
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
'use strict'; | |
class Score { | |
constructor(names) { | |
let alphabet = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']; | |
let lookup = new Map(); | |
alphabet.forEach(letter => lookup.set(letter, alphabet.indexOf(letter) + 1)); | |
this.names = names; | |
this.lookup = lookup; | |
} | |
getScore(name) { | |
let namePosition = this.names.indexOf(name) + 1; | |
let nameAsInts = name.split('').map(letter => this.lookup.get(letter)); | |
let score = nameAsInts.reduce((prev, curr) => prev + curr); | |
let total = score * namePosition; | |
if(name === 'COLIN') { console.log(`Sanity Check: ${name} => ${total}`); } | |
return total; | |
} | |
} | |
module.exports = Score; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment