CodeWars_Day02

Derek·2020년 12월 23일

CodeWars

목록 보기
2/2
post-thumbnail

Code wars #1

안녕하세요, Derek 입니다!

2일차입니다. recommend 로 나오는 문제를 풀어보았습니다.

Is a number prime?

Level : 6kyu

Define a function that takes one integer argument and returns logical value true or false depending on if the integer is a prime.
Per Wikipedia, a prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself.

간단합니다. 소수인지 확인해보랍니다.

Derek과 Clever Code의 코드

function isPrime(num) {
  if(num <= 1)
    return false;
  
  if(num == 2)
    return true;
  
  for(let i = 2 ; i < Math.sqrt(num) + 1 ; i++){
    if((num % i)){
      continue;
    }
    else{
      return false;
    }
  }
  return true;
}

비슷하게 풀었습니다. 다만, Math.sqrt(num) + 1 부분이 원래는 받는 숫자의 절반, 즉 num/2 였는데,
그렇게 했더니 시간초과가 나더군요.

그래서 제곱근으로 만들어 해결했습니다.




Sum of odd numbers

Level : 7kyu

수학문제가 많이 나오는군요.

문제는 아래와 같습니다.

Given the triangle of consecutive odd numbers:

             1
          3     5
       7     9    11
   13    15    17    19
21    23    25    27    29
...

rowSumOddNumbers(1); // 1
rowSumOddNumbers(2); // 3 + 5 = 8

처음에는 누적값으로 착각해 약간 헤맸습니다.

Derek과 Clever code 코드

function rowSumOddNumbers(n) {
  return Math.pow(n, 3);
}

누적인줄 알고 별 이상한 짓을 다했네요. 수학적 지식을 조금 가미해서 쉽게 풀었습니다.

거듭제곱의 사용법

이 친구만 정리해볼까요.

Math.pow(n, m);

이 식은 n의 m승을 말합니다. 끗.




Simple Pig Latin

Level : 5kyu

Move the first letter of each word to the end of it, then add "ay" to the end of the word. Leave punctuation marks untouched.

pigIt('Pig latin is cool'); // igPay atinlay siay oolcay
pigIt('Hello world !');     // elloHay orldway !

문자열을 가지고 이리저리 움직이는 문제입니다. 앞글자를 뒤로 붙이고, 뒤에 ay 를 붙이면 돼요.

Derek의 코드

function pigIt(str){
  let answer = "";
  const strArray = str.split(" ");
  strArray.forEach(str => {
    if((str >= "a" && str <= "z") || (str >= "A" && str <= "Z")){
      let tmp = str.slice(0, 1) + "ay";
      let rest = str.slice(1);
      answer += (rest + tmp);
      answer += " "
      }
    else{
      answer += (str + " ");
    }
  })
  return answer.slice(0, answer.length-1);
}

띄어쓰기를 기반으로 splice함수를 사용했습니다.

후에 특수기호가 아니라면 변수 tmprest를 사용해 문자열을 이동시켰고, 특수기호라면 아무런 행동없이 뒤에 띄어쓰기만 붙여주었습니다. (반환시 띄어쓰기가 있어야하므로)

마지막으로 반환할 때는 뒤에 한글자만 제거하여 반환했습니다. (띄어쓰기가 포함되어있음.)

Clever Code

function pigIt(str){
  return str.replace(/(\w)(\w*)(\s|$)/g, "\$2\$1ay\$3")
}

개쩌네요. 한줄로 하시는 고수님들 짱짱맨.

정규식... 그놈의 정규식!!

여기참고하면 된다. 진짜 엄청나게 복잡하다

간단히 설명하면, 다음 그림과 같다.

이걸 숙지하기는 어려울 것 같다. 틈틈히 보고 해보는 수밖에.

여기까지.

profile
Whereof one cannot speak, thereof one must be silent.

0개의 댓글