見習村03 - Highest Scoring Word

03 - Highest Scoring Word

Don’t say so much, just coding…

Instruction

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: 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.

Ruby

Init

1
2
3
def high(x)
# Code here
end

Sample Testing

1
2
3
4
5
6
7
8
describe "Basic Tests" do
it "should pass basic tests" do
Test.assert_equals(high('man i need a taxi up to ubud'), 'taxi')
Test.assert_equals(high('what time are we climbing up the volcano'), 'volcano')
Test.assert_equals(high('take me to semynak'), 'semynak')
Test.assert_equals(high('aaa b'), 'aaa')
end
end

Javascript

Init

1
2
3
function high(x){
// Code here
}

Sample Testing

1
2
3
4
5
Test.describe("Example tests",_=>{
Test.assertEquals(high('man i need a taxi up to ubud'), 'taxi');
Test.assertEquals(high('what time are we climbing up the volcano'), 'volcano');
Test.assertEquals(high('take me to semynak'), 'semynak');
});

Thinking

想法(1): 輸入的英文句子,可以先將每個字切開分群
想法(2): 再將每個群計算 ord 然後計算該群單詞 ord 總和

https://ithelp.ithome.com.tw/upload/images/20200918/2012082665vk5r7ygL.jpg
圖片來源:Unsplash Matt Ragland

Hint & Reference

Solution

Ruby

1
2
3
4
# Solution 1
def high(x)
x.split.max_by{ |x| x.chars.map{ |c| c.ord - 96}.sum }
end

Javascript

1
2
3
4
5
6
7
8
9
10
// Solution 1
function high(x){
let max = x.split(' ').map(
(s) => [...s].reduce(
(sum, s) => sum + s.charCodeAt() - 96, 0
)
)

return x.split(' ')[max.indexOf(Math.max(...max))];
}