[7kyu]Battle of the characters (

2017-07-09  本文已影响5人  君肄塵

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


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);
上一篇 下一篇

猜你喜欢

热点阅读