[7kyu]Battle of the characters (Medium)

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

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

  • 任务
    • 创建函数接收2个变量,比较并返回一个更大的变量。
  • 规则:
    1.每个字母都有自己的权重:
    A = 1, B = 2, ... Y = 25, Z = 26
    a = 0.5, b = 1, ... y = 12.5, z = 13
    2.只有大写字母能进行比较。
    3.总数(A + B + C + ...)大的一组被返回。
    4.如果两个组的值一样大,则返回 “Tie!”。
  • 例如:
    battle("One", "Two"); // => "Two"`
    battle("ONE", "NEO"); // => "Tie!"

  • 解答
  • 其一
const letter1 = '1ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const letter2 = '1abcdefghijklmnopqrstuvwxyz';
const sum = str => [...str].map(el=>letter1.indexOf(el) > 0 ? letter1.indexOf(el) : letter2.indexOf(el)/2).reduce((r,v)=>r+v,0);
const battle = (x, y) => sum(x) == sum(y) ? 'Tie!' :( sum(x) > sum(y) ? x : y);
  • 其二
function battle(x, y) {
      return calculate([...x].reduce(score, 0), [...y].reduce(score, 0));  
      function calculate(a, b) {
        return a === b ? 'Tie!' : a > b ? x : y;
      }  
      function score(acc, val) {
        const VALUES = { A:1,B:2,C:3,D:4,E:5,F:6,G:7,H:8,I:9,J:10,K:11,L:12,M:13,N:14,O:15,P:16,Q:17,R:18,S:19,T:20,U:21,V:22,W:23,X:24,Y:25,Z:26 };
        return acc + ((VALUES[val]||(VALUES[val.toUpperCase()]/2||0)));
      }
}
  • 其三
const battle = (x, y) => [x,"Tie!",y][Math.sign(val(y)-val(x))+1];
const val = x => [...x].reduce( (s,v) => s+ (" abcdefghijklmnopqrstuvwxyz".indexOf(v.toLowerCase())*(v>"Z"?.5:1)), 0);

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