Problem
- Given a string of words, you need to find the highest scoring word.
- 주어진 단어 문자열에서 가장 높은 점수를 받는 단어를 찾는다.
- Each letter of a word scores points according to its position in the alphabet.
- 각 단어의 글자는 알파벳의 위치에 따라 점수를 얻는다.
- 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.
Solution 01
function highestScoringWord(str) {
const alphabet = 'abcdefghijklmnopqrstuvwxyz';
let arr = str.split(' ');
let newArr = arr.map((word) => {
let sum = 0;
for (let i = 0; i < word.length; i++) {
sum += alphabet.indexOf(word[i]);
}
return sum;
});
return arr[newArr.indexOf(Math.max(...newArr))];
}
highestScoringWord('how are you'); // you
highestScoringWord('how have you been'); // you
highestScoringWord('how can i forget that'); // forget
Solution 02
function highestScoringWord(str) {
const alphabet = 'abcdefghijklmnopqrstuvwxyz';
let arr = str.split(' ');
let score = arr.map(i => [...i].map(i => alphabet.indexOf(i) + 1)).map(i => i.reduce((a, b) => a + b, 0));
return arr[score.indexOf(Math.max(...score))];
}
highestScoringWord('how are you'); // you
highestScoringWord('how have you been'); // you
highestScoringWord('how can i forget that'); // forget