1. Abbreviate a Two Word Namejavascript
/** 將一個名字的縮寫(大寫)返回。 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的郵件,每週都會有幾道推薦的題。但願之後能夠堅持下來.....less