codewars挑战系列二Love-vs-friendship-and

8次阅读

共计 1970 个字符,预计需要花费 5 分钟才能阅读完成。

1. Abbreviate a Two Word Name

/**
   将一个名字的缩写(大写)返回。Sam Harris => S.H
   
   思路:首先切割成字符串数组,然后拼接转成大写。*/
 function abbrevName(name){var nameArray = name.split(" ");
  return (nameArray[0][0] + "." + nameArray[1][0]).toUpperCase();}

2. Love vs friendship

/**
If `a = 1, b = 2, c = 3 ... z = 26`
Then`l + o + v + e = 54`
and`f + r + i + e + n + d + s + h + i + p = 108`
So`friendship`is twice stronger than`love`:-)
The input will always be in lowercase and never be empty.

思路:主要使用 charCodeAt 方法,计算每个字符。不过 friendship 正好是 108,不由想到了水浒。哈哈哈,太巧了~~~
*/
function wordsToMarks(str){
  let total = 0;
  for(let i = 0; i< str.length; i++){total += str.charCodeAt(i)-96
  }
  return total
}
// 也可以将字符串转为数组,求和
const wordsToMarks = s => [...s].reduce((res, c) => res += c.charCodeAt() - 96, 0)
// ps 扩展运算符真是好东西~~~

3. The Hunger Games – Foxes and Chickens (Poison)

链接:正则表达式(MDN)

/** 一个???? 吃????,???? 毒杀???? 的游戏。给定一个字符串,C 代表????,F 代表????。Foxes F eat chickens C  When foxes eat fox bait X they die. 
Fox bait is harmless to chickens. 
Chickens in cages [] are safe (unless a fox has got into the cage with them!)
Notes
*   Anything not a fox, a chicken, fox bait, or a cage is just dirt`.`
*   All cages are intact (not open-ended), and there are no cages inside other cages
*   The same fox bait can kill any number of foxes
*   A hungry fox will always eat as many chickens as he can get to, before he is tempted by the bait

看到这么一串符号,才感觉到正则的好处。恶补了“先行断言”、“后行断言”,终于鼓捣出来了....

思路:首先去掉所有符合条件的 C:1. 向左边查,有符合的 F 时,则用 '.' 替换 C。第一种情况,F 和 C 之间可能有 C 或者 .,对应的正则为 /(?<=F[C\.]*)C/g;当然,还可能有闭合的 [],对于里面的情况不用关心,表示为 \[[CFX.]*\]。然后和前面的拼接(\[[CFX.]*\][C\.]*)*,表示 F 和 C 之间可能有多个闭合[] 或者[C\.]*。最后 /(?<=F[C\.]*(\[[CFX.]*\][C\.]*)*)C/g 就包含了所有 F..[...]..C 的情况
2. 向右边查,有符合的 F 时,则用 '.' 替换 C。同样 /C(?=[C\.]*(\[[CFX.]*\][C\.]*)*F)/g 包含所有 C..[..]..F 的情况。然后,对比 F.....X 与 X.....F 的情况,正则表达式也较容易写出来。其实,只要一种情况考虑清楚,并写出正确的正则,剩余的就可以顺着思路写下来。不过正则表达式实在太费脑细胞了.... 看了看不用正则的思路,其实也挺麻烦的。光看代码就嫌长~~~
*/
var hungryFoxes = function(farm) {return farm.replace(/(?<=F[C\.]*(\[[CFX.]*\][C\.]*)*)C/g,'.')
            .replace(/C(?=[C\.]*(\[[CFX.]*\][C\.]*)*F)/g,'.')
            .replace(/(?<=X[F\.]*(\[[CFX.]*\][F\.]*)*)F/g,'.')
            .replace(/F(?=[F\.]*(\[[CFX.]*\][F\.]*)*X)/g,'.')
}

断断续续使用 codewars 也有段时间了,刚开始基本上是对 String 及 Array 方法的练习,后面渐渐有正则或者复杂些的逻辑。段位更高的是对象类的习题。之前订阅了 codewars 的邮件,每周都会有几道推荐的题。希望以后可以坚持下来 …..

正文完
 0