該算法題來自于 codewars【語言: javascript】帚呼,翻譯如有誤差,敬請諒解~
- 任務(wù)
- 創(chuàng)建函數(shù)接收2個變量舅锄,比較并返回一個更大的變量谜悟。
- 規(guī)則:
1.每個字母都有自己的權(quán)重:A = 1,B = 2疲酌,... Y = 25蜡峰,Z = 26以此類推。
2.只有大寫字母能進行比較。
3.總數(shù)(A + B + C + ...)大的一組被返回事示。
4.如果兩個組的值一樣大早像,則返回 “Tie!”。
- 解答
- 其一
const sum = str => [...str].map(el=>el.charCodeAt()).reduce((r,v)=>r+v,0);
const battle = (x, y) => sum(x) == sum(y) ? 'Tie!' :( sum(x) > sum(y) ? x : y);
- 其二
const total = word => [...word].reduce((a,b)=>a+(b.charCodeAt()),0)
const battle = (x, y) => total(x) > total(y) ? x : total(y) > total(x) ? y : 'Tie!'
- 其三
function battle(x, y) {
var sumx =0;
var i = x.length;
while (i--) {
sumx += x.charCodeAt(i);
}
var sumy =0;
i = y.length;
while (i--) {
sumy += y.charCodeAt(i);
}
if (sumx == sumy) return 'Tie!';
return sumx > sumy ? x: y;
}
- 其四
function battle(x, y) {
let r1 = x.split('').reduce( (a,b) => a+ "ABCDEFGHIJKLMNOPQRSTUVWXYZ".indexOf(b),0);
let r2 = y.split('').reduce( (a,b) => a+ "ABCDEFGHIJKLMNOPQRSTUVWXYZ".indexOf(b),0);
return r1 > r2 ? x : r1 < r2 ? y : "Tie!";
}
- 其五
function battle(x, y) {
var s1 = 0;
var s2 = 0;
x.split("").forEach(function(value){
s1+=value.charCodeAt()-96;
});
y.split("").forEach(function(value){
s2+=value.charCodeAt()-96;
});
return s1>s2? x:s1<s2?y:'Tie!'
}