# CodeWars 刷題 ###### tags: `2022 JS直播班` [TOC] ## 8kyu ### Square(n) Sum 日期:20221002 題目: ``` Complete the square sum function so that it squares each number passed into it and then sums the results together. For example, for [1, 2, 2] it should return 9 because 1^2 + 2^2 + 2^2 = 9. ``` 答案: ```javascript! squareSum = (array) => { let sum = 0; array.forEach(number => { sum += (number * number); }); return sum; } ``` --- ### Even or Odd 日期:20221002 題目: ``` Create a function that takes an integer as an argument and returns "Even" for even numbers or "Odd" for odd numbers. ``` 答案: ```javascript even_or_odd = number => number % 2 ? "Odd" : "Even"; ``` --- ### Basic Mathematical Operations 日期:20221004 題目: ``` 寫一個函式,讓以下三個參數可以輸出計算後的值。 ('+', 4, 7) --> 11 ('-', 15, 18) --> -3 ('*', 5, 5) --> 25 ('/', 49, 7) --> 7 ``` 答案: ```javascript let basicOp = (operation, value1, value2) => { switch(operation){ case '+': return value1 + value2; break; case '-': return value1 - value2; break; case '*': return value1 * value2; break; case '/': return value1 / value2; break; default: console.log("請重新輸入。"); }; }; ``` --- ### Keep Hydrated! 日期:20221004 題目: ``` Because Nathan knows it is important to stay hydrated, he drinks 0.5 litres of water per hour of cycling. You get given the time in hours and you need to return the number of litres Nathan will drink, rounded to the smallest value. For example: time = 3 ----> litres = 1 time = 6.7---> litres = 3 time = 11.8--> litres = 5 ``` - 這個出題挺讓人誤會的,`rounded to the smallest value`一開始以為是四捨五入,不過關。測試過後,使用`Math.floor()`或`Math.trunc()`皆可通關。 答案: ```javascript let litres = time => Math.floor(time * 0.5); // or let litres = time => Math.trunc(time * 0.5); ``` --- ### Logic Drills Traffic light 日期:20221005 題目: ``` 寫一個 function 可以傳入目前的燈號 green yellow red 傳入後將輸出下一個應該顯示的燈號 例如: green → yellow red → green ``` 答案: ```javascript //if else 簡單解法 let updateLight = (current) => { if(current == "green"){ return "yellow"; }else if(current == "yellow"){ return "red"; }else if( current == "red"){ return "green"; }; }; // indexOf 參考別人的解法 let updateLight = (current) => { const states = ['green', 'yellow', 'red']; const nextStateIndex =(states.indexOf(current) + 1) % (states.length); return states[nextStateIndex]; } ``` 解析: 1. indexOf 會回傳該陣列值的 index,若沒有值則回傳 -1。 1. 紅綠燈是依序變化,所以先找出下一個值的 index: states.indexOf(current) + 1。 1. 因為 red 下一個 index 為 3,因此要除以整個陣列的長度後的餘數才會得到第一個 index 0: % (states.length)。 --- ### Is he gonna survive? 日期:20221005 題目: ``` 兩顆子可擊敗一條龍,英雄可否存活?true or false ``` 答案: ```javascript let hero = (bullets, dragons) => bullets/2 >= dragons ? true : false; //or let hero = (bullets, dragons) => bullets/2 >= dragons; ``` --- ### Remove String Spaces 日期:20221006 題目: ``` Simple, remove the spaces from the string, then return the resultant string. ``` 答案: ```javascript // 1 let noSpace = x => x.replace(/\s+/g, ''); // 2 let noSpace = x => x.replace(/ /g, ''); // 3 let noSpace = x => x.split(' ').join(''); ``` [replace() 正規表達式補充](https://juejin.cn/post/6844904041923739656) --- ### Convert boolean values to strings 'Yes' or 'No'. 日期:20221006 題目: ``` Complete the method that takes a boolean value and return a "Yes" string for true, or a "No" string for false. ``` 答案: ```javascript let boolToWord = bool => bool == true ? 'Yes' : 'No'; ``` --- ### The Feast of Many Beasts 日期:20221008 題目: ``` 每隻動物參加盛宴都要帶一道菜來 不過有一條規則:菜名開頭和結尾的字母必須和動物名的開頭和結尾字母一樣 例如:chickadee (動物名) chocolate cake(菜名) 開頭和結尾分別是c和e 創建一個function feast內含兩個參數,分別是動物名(beast)和菜名(dish),function會回傳布林值 動物名(beast)和菜名(dish)必須要是小寫而且至少兩個字母,此外,不能是數字,開頭和結尾不能是 “ - “ 和空白 ``` 翻譯人:六角社群`hannahTW#2224` 答案: ```javascript let feast = (beast, dish) => { return beast.split('')[0] === dish.split('')[0] && beast.split('')[beast.length - 1] === dish.split('')[dish.length - 1]; } ``` 解說: `array[array.length - 1]` 可以取 Array 最後一個 index 的值。 --- ### Reversed Strings 日期:20221011 題目: ``` 反轉字串,EX: 'world' => 'dlrow' 'word' => 'drow' ``` 答案: ```javascript let solution = str => str.split('').reverse().join(''); ``` 網路搜尋最常見的解法,也簡單易懂,值得注意的是`split()`和`join()`的括弧內要添增字串符號`''`,不然會切分與增加失敗。 --- ### String cleaning 日期:20221011 題目: ``` 刪減字串中的數字,空格與特殊符號要保留。 ``` 答案: ```javascript let stringClean = s => s.replace(/\d*/g, ''); ``` 直覺想到用`replace()`,這題是考正規表達式吧XD。 另外分享一篇正規表達式的代碼說明與整理很清楚的文章:[正規表示式簡介 | QWERTY](http://gitqwerty777.github.io/regular-expression/#:~:text=%E6%AD%A3%E8%A6%8F%E8%A1%A8%E7%A4%BA%E5%BC%8F%E7%AF%84%E4%BE%8B%201%20%E6%95%B8%E5%AD%97%E6%88%96%E7%84%A1%E8%BC%B8%E5%85%A5%EF%BC%9A%20%5E%20%5B0-9%5D%2A%24%202%20m%20%E5%88%B0,%5B0-9%5D%7C%20%5B01%5D%3F%20%5B0-9%5D%20%5B0-9%5D%3F%29%29%2A%24%20...%207%20%E5%8F%AF%E4%BB%A5%E6%80%9D%E8%80%83%E4%B8%8B%E5%88%97%E5%85%A9%E9%A1%8C%EF%BC%8C%E6%98%AF%E5%90%A6%E6%9C%89%E6%9B%B4%E5%A5%BD%E7%9A%84%E5%AF%AB%E6%B3%95%20) --- ### Count of positives sum of negatives - 正數負數總和 日期: 20221107 題目: ``` 定義一組陣列數字,計算第一個元素是正數的數量、第二個元素是負數的總和。 如果元素為0 既不是正數也不是負數。 陣列有可能為空或 null。 ``` 答案: ```javascript let countPositivesSumNegatives = input => { let sum1 = 0; let sum2 = 0; if(input === null || input.length === 0){ return []; }else { input.forEach(i => i > 0 ? sum1 ++ : sum2 += i) return [sum1, sum2]; } }; ``` --- ### loop statement --while and do..while -- While迴圈 日期: 20221114 題目: ``` 使用 while 方式,跑第一次將星星加入str左邊,第二次將星星加入str右邊。 ``` 答案: ``` let padIt = (str, n) => { let num = 0; while(num < n){ num % 2 ? str = str + '*' : str = '*' + str; num++; } return str; } ``` --- ## 7kyu ### String ends with? 日期:20221008 題目: ``` 提供兩個字串參數,第二的參數要等同於第一個參數的結尾。 Examples: solution('abc', 'bc') // returns true solution('abc', 'd') // returns false ``` 答案: ```javascript let solution = (str, ending) => str.endsWith(ending); ``` 補充 MDN 對`String.prototype.endsWith()` 的說明: [連結](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith) --- ### String ends with? 日期:20221011 題目: ``` 讓數字由大到小,做降序排列。 ``` 答案: ```javascript // 我的解法: let descendingOrder = n => { let convertN = n.toString(); let array = convertN.split(''); let compare = (a, b) => b - a; let sortArray = array.sort(compare); let joinArray = sortArray.join(''); let convertNum = Number(joinArray); return convertNum; } // sort()解決陣列排序與印出: n = [1,0,2,1]; let compare = (a, b) => b - a; let descendingOrder = n => n.sort(compare); // 解出後看大神的一行解法: let descendingOrder = n => parseInt(n.toString().split('').sort().reverse().join('')); ``` 使用`sort((a, b) => b - a)`做降序排列,但只支援陣列。 所以先將數字轉字串再轉陣列,再將陣列轉字串再轉數字。 --- ### Cats and shelves - 貓咪和架子 日期:20221011 題目說明(配網站的圖): * 架子為左右左右往上排序。 * 貓咪可以一次跳 3 個架子的高度,例如: 1 → 2 或 1 → 4。 * 但是貓咪不能直接爬頭頂上的架子,例如: 1 → 3 不行,一定要 1 → 2 → 3。 * 請算出不同號碼的架子(開始與結束)之間,貓咪最少要跳幾次才能成功抵達? 答案: ```javascript! let solution = (start, finish) => { let shelveNum = finish - start ; return Math.floor(shelveNum/3) + (shelveNum % 3); } ``` 本來是想算出數字差除以三後,有餘數就加一(再跳一次),沒有餘數則取除數。 但有個陷阱是貓咪不能直接跳頭頂上的架子,等於要多跳。 所以應該為寫出「取除數+取餘數」的算式。 考解題和計算能力QQ --- ### Printer Errors 影印機錯誤 日期:20221022 題目: ``` 字符串只要出現不是來自 a to m.,例如aaaxbbbbyyhwawiwjjjwwm字母就會出錯。 您必須編寫一個函數printer_error,回傳結果的分子是錯誤數,分母是字符串的長度。不要將此分數簡化為更簡單的表達式。 該字符串的長度大於或等於 1,並且僅包含從a到 的字母z。 例子: s="aaabbbbhaijjjm" printer_error(s) => "0/14" s="aaaxbbbbyyhwawiwjjjwwm" printer_error(s) => "8/22" ``` 答案: ```javascript let printerError = s => { let strLength = s.length; let errorLength = s.split('').filter(x => /^[^a-m]*$/g.test(x)).length; return `${errorLength}/${strLength}`; } ``` 卡有點久。 主要是可以用中文說出流程,卻不知道該使用哪個程式碼表現。 1. 計算 s 的長度 2. 用正規表達式找出不符合的字母 ← 卡在這裡 3. 計算不符合字母的長度 最後找到`test()`方法來判斷正規表達式,並用`filter()`篩選出來,耶! 解出後看一下大神的答案: 1. ``${s.replace(/[a-m]/gi, "").length}/${s.length}``,使用`replace()`替換其他符號再計算長度,不用彎彎繞繞那麼多,真的聰明! 2. ``${(s.match(/[^a-m]/g) || []).length}/${s.length}``,原來可以使用`match()`來找出符合正規表達式的條件!也加上`||`判斷來計算長度,也是我沒想到的。 寫出自己的程式碼後,再看別人的解答也很有趣呢。 但不一定會照單全收,只是未來也可以用在其他情境上,讚讚。 --- ### Testing 1-2-3 - 測試 1-2-3 日期:20221026 題目: ``` 題目重點翻譯: 讓列表內的值添加有序數字,並注意冒號和空格。如下: [] --> [] ["a", "b", "c"] --> ["1: a", "2: b", "3: c"] ``` 答案: ```javascript let number = array => array.map((value, index) => `${index + 1}: ${value}`); ``` #### 解題方式 一開始使用: ``` let number = array => array.map(v => array.indexOf(v)+1 +": "+v); ``` 出現以下錯誤: ``` [ '1: ', '1: ', '1: ', '1: ', '1: ' ] --> [ '1: ', '2: ', '3: ', '4: ', '5: ' ] ``` 上網找到這位[大神](https://www.youtube.com/watch?v=lsxyIgSBGok)的解法,才知道應該熟悉`array.map()`的語法,才能得到最佳解。 #### `map()`方法: 這題可以訓練 `array.map()` 的語法,[參考資料](https://www.runoob.com/jsref/jsref-map.html): ``` array.map(function(currentValue,index,arr), thisValue) ``` - 可對陣列內每一個元素加工後回傳,組合成一個新的陣列。 - 參數為: 1. `function`: 函式內的參數分別為: `currentValue`, `index`, `array`。 2. `thisValue`: 執行 callback 時,用於 this 的值,被執行的對象會回傳給函數。 **補充:** `thisValue`[參考資料](https://blog.csdn.net/qq_36453396/article/details/106017250): - 第二行程式碼可判斷所有 currentValue 是否都大於 1,但因為index 0 為 1,沒有大於 1,所以回傳 false。 - 第六行程式碼可判斷所有 currentValue 是否都大於 1,[1, 2, 3] 皆大於 0,回傳 true。 因此利用參數的參數進行加工,便可得到我們要的回傳值,理解過後挺方便的。 --- ### Filter the number 日期:20221028 題目: ``` 回傳字串裡的阿拉伯數字。 filterString("123") // 123 filterString("a1b2c3") // 123 ``` 答案: ```javascript let filterString = value => parseInt(value.split('').filter(n => !isNaN(n)).join('')); ``` --- ### V A P O R C O D E 日期: 20221103 題目: ``` 寫一個函式將代入的字串轉換為 V A P O R W A V E 句子 V A P O R W A V E 為所有字母大寫,字母和字母中間需有兩個空格(含特殊符號) EX: "Lets go to the movies" --> "L E T S G O T O T H E M O V I E S" "Why isn't my code working?" --> "W H Y I S N ' T M Y C O D E W O R K I N G ?" ``` 答案: ```javascript let vaporcode = string => string.replace(/ /g, '').toUpperCase().split('').join(' '); ``` 土法煉鋼的解法。 --- ### Love vs friendship - 愛情 vs 友情 日期: 20221103 題目: ``` 讓每個英文字母都賦予一個數字,寫一個 funtion 來計算字母的加總。 EX: l + o + v + e = 54 f + r + i + e + n + d + s + h + i + p = 108 wordsToMarks("family") // 66 ``` ```javascript let wordsToMarks = string => [...string].reduce((total, currentValue) =>total += currentValue.charCodeAt(0)-96, 0); ``` 透過這題,第一次知道 ASCII, charCodeAt(),也嘗試 [...arr], reduce 的寫法。 --- ### Likes Vs Dislikes 日期: 20221108 題目: ``` 這題在模擬 Youtube 的喜歡不喜歡按鈕,會提供一個操作的陣列,寫一個 function 來回傳最終結果到底是按下喜歡還是不喜歡 思路在於如果先按 Like 在按 Dislike,會回傳後者 Dislike 而相同狀態按兩次則取消點擊,回傳 Nothing 所以在發現公式前可以透過遍歷去模擬點擊順序來回傳最終狀態值 likeOrDislike([Dislike]) => Dislike likeOrDislike([Like,Like]) => Nothing likeOrDislike([Dislike,Like]) => Like likeOrDislike([Like,Dislike,Dislike]) => Nothing ``` 解題: ```javascript let likeOrDislike = buttons => buttons.reduce((acc, cur) => acc == cur ? 'Nothing' : cur, 'Nothing'); ``` 透過同學的協助解這題。 ``` reduce((a,b)) a 參數 return 上一個迴圈的判斷結果 所以 like(a) 等於 like(b) 為 nothing dislike(a) 等於 dislike(b) 為 nothing like(a) 不等於 dislike(b) 為 dislike(b) dislike(a) 不等於 like(b) 為 like(b) ``` --- ### Exes and Ohs-井字棋(OOXX) 日期:20221109 題目: ``` 在不區分大小寫的前提下,判斷 string 中 'X' 和 'O' 的數量是否相等,返回布林值 ``` 答案: ```javascript let XO = str => { const {x, o} = str.toLowerCase().split('').reduce((acc, cur) => { acc[cur] ? acc[cur] ++ : acc[cur] = 1; return acc; }, {}) return x === o ? true : false; } ``` 這次學到 `{x,o}=reduce()` 的寫法,輕鬆獲得 x 和 o 得值。 --- # Incrementer - 加法器 日期: 20221112 題目: ``` 寫一個 function 會帶入陣列參數,將陣列每一個數字按照順序 +1, +2, +3 ... 如 [1, 2, 3] --> [2, 4, 6] # [1+1, 2+2, 3+3] [4, 6, 9, 1, 3] --> [5, 8, 2, 5, 8] # [4+1, 6+2, 9+3, 1+4, 3+5] # 9+3 = 12 --> 2 若遇到結果是超過個位數則取個位數數字 如上述 9+3 = 12 則取 2 ``` 答案: ```javascript let incrementer = nums => nums.map((item, index) => parseInt(item + (index + 1)) % 10); ``` javascript 取個位數的方式 `parseInt(num % 10)`。 --- ## 6kyu ### Counting Duplicates 日期:20221029 題目: ``` 計算字串中,有幾個重複出現的元素? EX: "abcde" -> 0,沒有任何重複。 "aabbcde" -> 2,a 跟 b 重複,共兩個。 "aabBcde" -> 2,a 跟 b 重複,共兩個。大寫 B 等同於 小寫 b。 "aA11" -> 2,a 跟 1 重複,共兩個。 "ABBA" -> 2,A 跟 B 重複,共兩個。 ``` 答案: ```javascript let duplicateCount = text => { let total=0; let obj = text.toLowerCase().split('').reduce((accumulator, currentValue)=>{ if(accumulator[currentValue]) { accumulator[currentValue] ++; } else { accumulator[currentValue] = 1; } return accumulator; }, {}); Object.values(obj).forEach(i => i >= 2 ? total++ : total); return total; } ``` 大約花兩小時解題。 就不另外想一行解法,免得到時回看看不懂自己的邏輯。 也是第一次嘗試`reduce()`方法,有熟悉一點,挺高興的! 解出來後看大神們的答案都寫好短喔😢 ,也是有進步空間,繼續加油! --- ### Count characters in your string 日期: 20221106 題目: ``` 計算字串中同樣字的數量, 例:"aba" -> {'a': 2, 'b': 1},如果字串是空的則返回空物件。 ``` 答案: ```javascript let count = string => { let obj = {}; string.split('').forEach( i => obj[i] ? obj[i] += 1 : obj[i] = 1); return obj; } ``` --- ### Break camelCase -打破駱駝峰 日期: 20221112 題目: ``` 如果輸入字串為駱駝峰,在大寫英文字母前加入空格 Ex: "camelCasing" => "camel Casing" "identifier" => "identifier" "" => "" ``` 答案: ```javascript let solution = string => string.replace(/([A-Z])/g, ' $1'); ``` 直覺想到 `replace()` 來解,但不知道如何解決大寫被替代的困難,查了一下正規表達式可以使用「群組」來做元素的替代。 [正規表示式 (Regular Expression) 語法整理](http://www.vixual.net/blog/archives/211) **群組**: 1. 可以使用小括號` ( ... )` 將既有的規則組合成一個「群組」 2. 建立規則群組之後,可再以此群組為基礎,套用其它的規則 3. 可以用 `\1 ... \9` 來代表前面符合的群組 4. 當要儲存或取代比對的內容時,可以用` $1 .. $9` (或` \1 ... \9`) 來代表各群組