Code Wars: Highest Scoring Word (passed on first try!)
https://www.codewars.com/kata/57eb8fcdf670e99d9b000272/train/javascript
Given a string of words, you need to find the highest scoring word.
Each letter of a word scores points according to it's position in the alphabet:
a = 1, b = 2, c = 3
etc.
You need to return the highest scoring word as a string.
If two words score the same, return the word that appears earliest in the original string.
All letters will be lowercase and all inputs will be valid.
function high(x){
let arr = x.split(" ");
let largest; //stores the current string with largest score
let totalScore = 0; //stores the current largest score for that particular string
//create an array of lowercase alphabets
let alphaArr = [];
for (let i = 0; i < 26; i++) {
alphaArr.push(String.fromCharCode(97 + i));
}
for (let i = arr.length - 1; i >= 0; i--) { //loops through array
let letterScore = 0; //stores the total score for each string. Resets at each arr element.
for (let j = 0; j < arr[i].length; j++) { //loops through each letter of element
letterScore += alphaArr.indexOf(arr[i].charAt(j)) + 1;
}
if (letterScore >= totalScore) {
totalScore = letterScore;
largest = arr[i];
}
}
return largest;
}
Comments
Post a Comment