CodeWar Weekly - 0217~0223

CodeWar Weekly[0217-0223]

6kyu Highest Scoring Word

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.

解題思考:取字母轉成數字會是最大值的詞,取 = max_by,後面的條件就要依照先轉數字 ord,然後在計算… ex: sum, reduce, inject

參考方法 & 學習筆記

Ruby

max_by

max_by {|obj| block } → obj || max_by → an_enumerator
Returns the object in enum that gives the maximum value from the given block.
If no block is given, an enumerator is returned instead.

1
2
a = %w(albatross dog horse)
a.max_by {|x| x.length } #=> "albatross"

max 的不同在,能不能在設定條件而已,原本的 max 只會取開頭字母最大的 ord

JavaScript

charCodeAt()

The charCodeAt() method returns an integer between 0 and 65535 representing the UTF-16 code unit at the given index.

1
2
3
4
5
6
const sentence = 'The quick brown fox jumps over the lazy dog.';

const index = 4;

console.log('The character code ' + sentence.charCodeAt(index) + ' is equal to ' + sentence.charAt(index));
// expected output: "The character code 113 is equal to q"

ord

ord → self
Returns the int itself.

1
?a.ord    #=> 97

Ruby

Solution(1):

1
2
3
def high(x)
x.split.max_by{ |i| i.chars.map{ | j | j.ord - 96 }.sum }
end

Solution(2):

1
2
3
4
5
6
7
def high(x)
x.split.max_by { |w| score_word(w) }
end

def score_word(word)
word.chars.inject(0) { |sum, ch| sum + (ch.ord - 96) }
end

JavaScript

Solution(1):

1
2
3
4
5
6
7
8
9
function high(x){
return x.split(' ').reduce((accum, current) => {
return score(current) > score(accum) ? current:accum;
})
}

function score(word){
return word.split('').reduce((accum,current) => { return accum+(current.charCodeAt()-96) }, 0)
}

Solution(2):

1
2
3
4
function high(s){
let as = s.split(' ').map(s=>[...s].reduce((a,b)=>a+b.charCodeAt(0)-96,0));
return s.split(' ')[as.indexOf(Math.max(...as))];
}

參考資料