7/19일 codewars 문제

samuel Jo·2023년 7월 19일
0

codewars

목록 보기
39/46

계속 밤에 풀다보니까 하루가 지나서 올리게 됨..

오늘의 문제는 3가지.

1. reverseWords

DESCRIPTION:

Complete the function that accepts a string parameter, and reverses each word in the string. All spaces in the string should be retained.

Examples

"This is an example!" ==> "sihT si na !elpmaxe"
"double spaces" ==> "elbuod secaps"

function reverseWords(str) {
  let reversedStr = str
    .split("")
    .reverse()
    .join("");

  let reversedWords = reversedStr.split(" ").reverse().join(" ");
  return reversedWords;
}

이렇게까지만 생각했는데 찍어보니

  let reversedStr = str
    .split("")
    .reverse();

"This is an example!" 이런 문자열이 왔다 치면,
바로 위코드로는 "example! an is This" 이렇게 결과 값이 나온다. 이걸 다시 split(" ")으로 단어별로 나누고 다시 reverse()를 해주고 , join("")을 통해 문자열로 만들어줘야함!


2.Find the unique number

DESCRIPTION:

There is an array with some numbers. All numbers are equal except for one. Try to find it!
findUniq([ 1, 1, 1, 2, 1, 1 ]) === 2
findUniq([ 0, 0, 0.55, 0, 0 ]) === 0.55
It’s guaranteed that array contains at least 3 numbers.
The tests contain some very huge arrays, so think about performance.

This is the first kata in series:

Find the unique number (this kata)
Find the unique string
Find The Unique

위문제들도 풀어보기.

2.1 처음 생각한방법.

일단 중복을 제거하기위해 Set을 사용.
Set으로 만들고 그에 대한 요소를 순회하는 for...of 문으로 indexOf()/lastIndexOf를 통해 중복되지않은 요소를 찾고 요소를 반환.하는 방법.
indexOf()는 앞에서부터 lastIndexOf는 뒤에서부터 고로 같은 인덱스값을 가지면 유일한 요소.

function findUniq(arr) {
  // Set을 사용하여 중복을 제거한 배열을 생성
  const uniqueNumbers = new Set(arr);
  
  // Set에서 유니크한 숫자를 찾아 반환
  for (let num of uniqueNumbers) {
    if (arr.indexOf(num) === arr.lastIndexOf(num)) {
      return num;
    }
  }
}

2.2 두번째로 생각한방법

function findUniq(arr) {
  return arr.find(n => arr.indexOf(n) === arr.lastIndexOf(n));
}

find()메서드를 통해 짠 코드지만 이건 시간복잡도가 O(n^2)이므로 요구사항에서 테스트코드에서 엄청 큰 배열이 있으니 성능을 신경써라는 항목이 있었기에 적합하진 않은 코드같다.

find()의 시간복잡도 O(n)을 갖고, 메서드 안에서 arr.indexOf()와 arr.lastIndexOf()가 각각 호출되어 O(n^2)이므로 위코드가 성능적으로 좋다 볼 수 있다.


3. give me diamonds

DESCRIPTION:
Jamie is a programmer, and James' girlfriend. She likes diamonds, and wants a diamond string from James. Since James doesn't know how to make this happen, he needs your help.

Task
You need to return a string that looks like a diamond shape when printed on the screen, using asterisk (*) characters. Trailing spaces should be removed, and every line must be terminated with a newline character (\n).
Return null/nil/None/... if the input is an even number or negative, as it is not possible to print a diamond of even or negative size.

이문제는 얼마전 푼 문제와 거의 비슷해서 금방 풀었다.

function diamond(n) {
  if (n % 2 === 0 || n < 1) {
    return null;
  }

  const diamondArr = [];
  const middleIndex = Math.floor(n / 2);

  for (let i = 0; i < n; i++) {
    const spaces = Math.abs(middleIndex - i);
    const stars = n - 2 * spaces;

    diamondArr.push(' '.repeat(spaces) + '*'.repeat(stars) + '\n');
  }

  return diamondArr.join('');
}

다만 조건이 홀수여야 하는 부분이 추가됐다.

profile
step by step

1개의 댓글

comment-user-thumbnail
2023년 7월 19일

항상 좋은 글 감사합니다.

답글 달기