저장을 습관화

프로그래머스 LV.0 할 일 목록 본문

코딩 테스트/프로그래머스 - 자바스크립트

프로그래머스 LV.0 할 일 목록

ctrs 2023. 9. 17. 17:51

프로그래머스 LV.0 할 일 목록

https://school.programmers.co.kr/learn/courses/30/lessons/181885

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

1. 문제 명

할 일 목록


2. 문제 설명

오늘 해야 할 일이 담긴 문자열 배열 todo_list와 각각의 일을 지금 마쳤는지를 나타내는 boolean 배열 finished가 매개변수로 주어질 때, todo_list에서 아직 마치지 못한 일들을 순서대로 담은 문자열 배열을 return 하는 solution 함수를 작성해 주세요.


3. 제한 사항

- 1 ≤ todo_list의 길이 1 ≤ 100

- 2 ≤ todo_list의 원소의 길이 ≤ 20

- todo_list의 원소는 영소문자로만 이루어져 있습니다.

- todo_list의 원소는 모두 서로 다릅니다.

- finished[i]는 true 또는 false이고 true는 todo_list[i]를 마쳤음을, false는 아직 마치지 못했음을 나타냅니다.

- 아직 마치지 못한 일이 적어도 하나 있습니다.


4. 예시

todo_list finished result
["problemsolving", "practiceguitar", "swim", "studygraph"] [true, false, true, false] ["practiceguitar", "studygraph"]


5. 기본 제공 코드

function solution(todo_list, finished) {
    var answer = [];
    return answer;
}


6. 제출한 내 답

const solution = (todo_list, finished) => {
  let a = [];
  finished.forEach((v, i) => {
    return v === false ? a.push(todo_list[i]) : "";
  });
  return a;
};

 

6-2. VSC에 작성한 내용

const solution = (todo_list, finished) => {
  let a = [];
  finished.forEach((v, i) => {
    return v === false ? a.push(todo_list[i]) : "";
  });
  return a;
};

// 테스트
console.log(
  solution(
    ["problemsolving", "practiceguitar", "swim", "studygraph"],
    [true, false, true, false]
  )
);


7. 특이사항

처음에 이렇게 작성해봤는데

const solution = (todo_list, finished) => {
  return finished.filter((v, i) => {
    if (v === false) {
      console.log(i)
      return todo_list[i];
    }
  });
};

// 테스트
console.log(
  solution(
    ["problemsolving", "practiceguitar", "swim", "studygraph"],
    [true, false, true, false]
  )
);

결과가 [ false, false ]가 나왔다.

console.log(i)는 현재 인덱스 번호를 잘 출력하는데

그대로 써먹을 수는 없는걸까


8. 다른 사람이 작성한 답

8-1. map과 filter 합성

const solution = (todo_list, finished) => {
  return finished
    .map((v, i) => {
      if (v === false) {
        return todo_list[i];
      }
    })
    .filter((v) => v !== undefined);
};

map은 원본 배열과 같은 길이의 배열을 리턴한다.

만약 조건에 맞지 않는 요소는 undefined로써 반환한다.

 

이후 map의 처리 결과를 filter를 통해 undefined 요소를 제거한다.

 

왜 filter에서는 todo_list[i]를 사용할 수 있었는데

map에서는 todo_list[i]가 사용 가능했던 걸까?

 

8-2.

function solution(todo_list, finished) {
    var answer = [];
    return todo_list.filter((e,i) => !finished[i]);
}