[7kyu]Battle of the characters (Easy)

该算法题来自于 codewars【语言: javascript】,翻译如有误差,敬请谅解~

[7kyu]Battle of the characters (Easy)_第1张图片

  • 任务
    • 创建函数接收2个变量,比较并返回一个更大的变量。
  • 规则:
    1.每个字母都有自己的权重:A = 1,B = 2,... Y = 25,Z = 26以此类推。
    2.只有大写字母能进行比较。
    3.总数(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

你可能感兴趣的:([7kyu]Battle of the characters (Easy))