Chiayin's blog

【刷題】CodeWars-8kyu

字數統計: 1.1k閱讀時間: 5 min
2022/11/02

紀錄 CodeWars 的刷題過程、解答、衍伸想法。
不定期更新唷~。

8kyu

Square(n) Sum

日期:20221002
題目:

1
2
3
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.

答案:

1
2
3
4
5
6
7
squareSum = (array) => {
let sum = 0;
array.forEach(number => {
sum += (number * number);
});
return sum;
}

Even or Odd

日期:20221002
題目:

1
Create a function that takes an integer as an argument and returns "Even" for even numbers or "Odd" for odd numbers.

答案:

1
even_or_odd = number =>  number % 2 ?  "Odd" : "Even";

Basic Mathematical Operations

日期:20221004
題目:

1
2
3
4
5
寫一個函式,讓以下三個參數可以輸出計算後的值。
('+', 4, 7) --> 11
('-', 15, 18) --> -3
('*', 5, 5) --> 25
('/', 49, 7) --> 7

答案:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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
題目:

1
2
3
4
5
6
7
8
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()皆可通關。

答案:

1
2
3
let litres = time => Math.floor(time * 0.5);
// or
let litres = time => Math.trunc(time * 0.5);

Logic Drills Traffic light

日期:20221005
題目:

1
2
3
寫一個 function 可以傳入目前的燈號 green yellow red
傳入後將輸出下一個應該顯示的燈號
例如: green → yellow red → green

答案:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//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。
  2. 紅綠燈是依序變化,所以先找出下一個值的 index: states.indexOf(current) + 1。
  3. 因為 red 下一個 index 為 3,因此要除以整個陣列的長度後的餘數才會得到第一個 index 0: % (states.length)。

Is he gonna survive?

日期:20221005
題目:

1
兩顆子可擊敗一條龍,英雄可否存活?true or false

答案:

1
2
3
let hero = (bullets, dragons) => bullets/2 >= dragons ? true : false;
//or
let hero = (bullets, dragons) => bullets/2 >= dragons;

Remove String Spaces

日期:20221006
題目:

1
Simple, remove the spaces from the string, then return the resultant string.

答案:

1
2
3
4
5
6
// 1
let noSpace = x => x.replace(/\s+/g, '');
// 2
let noSpace = x => x.replace(/ /g, '');
// 3
let noSpace = x => x.split(' ').join('');

replace() 正規表達式補充


Convert boolean values to strings ‘Yes’ or ‘No’.

日期:20221006
題目:

1
Complete the method that takes a boolean value and return a "Yes" string for true, or a "No" string for false.

答案:

1
let boolToWord = bool => bool == true ? 'Yes' : 'No';

The Feast of Many Beasts

日期:20221008
題目:

1
2
3
4
5
6
7
8
每隻動物參加盛宴都要帶一道菜來
不過有一條規則:菜名開頭和結尾的字母必須和動物名的開頭和結尾字母一樣
例如:chickadee (動物名)
chocolate cake(菜名)
開頭和結尾分別是c和e

創建一個function feast內含兩個參數,分別是動物名(beast)和菜名(dish),function會回傳布林值
動物名(beast)和菜名(dish)必須要是小寫而且至少兩個字母,此外,不能是數字,開頭和結尾不能是 “ - “ 和空白

翻譯人:六角社群hannahTW#2224

答案:

1
2
3
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
題目:

1
2
3
反轉字串,EX:
'world' => 'dlrow'
'word' => 'drow'

答案:

1
let solution = str => str.split('').reverse().join('');

網路搜尋最常見的解法,也簡單易懂,值得注意的是split()join()的括弧內要添增字串符號'',不然會切分與增加失敗。


String cleaning

日期:20221011
題目:

1
刪減字串中的數字,空格與特殊符號要保留。

答案:

1
let stringClean = s => s.replace(/\d*/g, '');

直覺想到用replace(),這題是考正規表達式吧XD。
另外分享一篇正規表達式的代碼說明與整理很清楚的文章:正規表示式簡介 | QWERTY


發佈日期:2022-11-02

更新日期:2022-11-02

CATALOG
  1. 1. 8kyu
    1. 1.1. Square(n) Sum
    2. 1.2. Even or Odd
    3. 1.3. Basic Mathematical Operations
    4. 1.4. Keep Hydrated!
    5. 1.5. Logic Drills Traffic light
    6. 1.6. Is he gonna survive?
    7. 1.7. Remove String Spaces
    8. 1.8. Convert boolean values to strings ‘Yes’ or ‘No’.
    9. 1.9. The Feast of Many Beasts
    10. 1.10. Reversed Strings
    11. 1.11. String cleaning