/**
将一个名字的缩写(大写)返回。
Sam Harris => S.H
思路:首先切割成字符串数组,然后拼接转成大写。
*/
function abbrevName(name){
var nameArray = name.split(" ");
return (nameArray[0][0] + "." + nameArray[1][0]).toUpperCase();
}
/**
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的邮件,每周都会有几道推荐的题。希望以后可以坚持下来.....
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。