codewars练习(javascript)-2021/2/21
作者:互联网
文章目录
codewars-js练习
2021/2/21
github 地址
【1】<6kyu>【Prize Draw】
Each letter of a firstname has a value which is its rank in the English alphabet. A
and a
have rank 1
, B
and b
rank 2
and so on.
The length of the firstname is added to the sum of these ranks hence a number som
.
An array of random weights is linked to the firstnames and each som
is multiplied by its corresponding weight to get what they call a winning number
.
名字中的每个字母都有一个值,这个值就是它在英语字母表中的排名。A和A的等级是1,B和B的等级是2,以此类推。firstname的长度加到这些级别的总和,因此是一个数字som。一组随机权重与名字相连,每个som乘以相应的权重,得到他们所谓的中奖号码。
参数:st是名字的字符串,我们是权重的数组,n是秩的数组
return: rank为n的参与者的名字(rank从1开始编号)
先算出每个的中奖号码,进行排序,最后返回rank为n的名字
example:
names: "COLIN,AMANDBA,AMANDAB,CAROL,PauL,JOSEPH"
weights: [1, 4, 4, 5, 2, 1]
PauL -> som = length of firstname + 16 + 1 + 21 + 12 = 4 + 50 -> 54
The *weight* associated with PauL is 2 so PauL's *winning number* is 54 * 2 = 108.
solution
<script type="text/javascript">
function rank(st, we, n) {
let names = st.split(',')
if (!st.length) return 'No participants'
if (names.length < n) return 'Not enough participants'
return names.map((_, i) => ({
name: _,
s: [..._.toLowerCase()].reduce((a, b) => a + b.charCodeAt() - 95, 0) * we[i]
}))
.sort((a, b) => a.name > b.name)
.sort((a, b) => b.s - a.s)
[n - 1].name
}
// 验证
console.log(rank("Addison,Jayden,Sofia,Michael,Andrew,Lily,Benjamin", [4, 2, 1, 4, 3, 1, 2], 4));// "Benjamin"
</script>
以上为大佬的思路。
标签:return,name,javascript,som,rank,length,2021,codewars,PauL 来源: https://blog.csdn.net/FemaleHacker/article/details/113914229