본문 바로가기

Programming

[Algorithm] 프로그래머스 - level1 <체육복>

<문제소개>

  • 문제명 : 체육복
  • 사이트 : 프로그래머스
  • 난이도 : level 1
  • 사용 언어 : javascript

<문제 풀이>

접근 방식

  1. 여벌의 체육복이 있는데 도난당한 학생의 경우 lost와 reserve 모두에서 제외한다.
    (입을 체육복이 있으나 더이상 빌려줄 수 없기 때문)
  2. lost 각각의 요소에 +1, -1을 한 값이 reserve에 있는지 확인하고
    있으면 체육복이 없는 학생 수  - 1, 일치하는 reserve 값을 reserve에서 제거

<내 코드>

function solution(n, lost, reserve) {
    let students = n;
    const realReserve = [];
    
    reserve.forEach((res) => {
        if (lost.indexOf(res) === -1) {
            realReserve.push(res);
        } else {
            lost.splice(lost.indexOf(res), 1);
        }
    });

    let noClothStudents = lost.length;
    
    for (let i = 0; i < lost.length; i++) {
        if (realReserve.indexOf(lost[i] - 1) !== -1) {
            realReserve.splice(realReserve.indexOf(lost[i] - 1), 1);
            noClothStudents--;
        } else if (realReserve.indexOf(lost[i] + 1) !== -1) {
            realReserve.splice(realReserve.indexOf(lost[i] + 1), 1);
            noClothStudents--;
        }
    }

    return students - noClothStudents;
}

 


<보완할 점>

- 어떤 배열을 반복문으로 돌릴 때 조건에 따라 해야하는 작업이 배열의 요소를 제거 또는 추가해야하는 경우

배열이 변화하면 조건이 제대로 동작하지 않을 수 있다.

→ 배열이 변화하지 않도록 하거나, 배열의 변화와 상관없이 작동하도록 만들어야한다.

 

- 배열에 원소가 포함되어있는지 확인하고싶을 때

arr.indexOf(item) !== -1

로 찾기보다

arr.includes(item) (=true / false)

로 조건을 검사하자.