프로그래머스 문제 풀이 체육복 (JS)

devmomo·2021년 3월 5일
0

알고리즘

목록 보기
1/52
post-thumbnail

문제분석

전체 학생 수 n
체육복을 도난당한 학생들의 번호가 담긴 배열 lost
여벌의 체육복을 가져온 학생들의 번호가 담긴 배열 reserve

체육 수업을 들을 수 있는 학생의 최댓값을 return 하도록 solution 짜기

제한사항

전체 학생의 수는 2명이상 30명 이하
체육복을 도난당한 학생의 수는 1명 이상 n명 이하 중복 불가
여벌의 체육복을 가져온 학생의 수는 1명 이상 n명 이하 중복 불가
여벌 체육복이 있는 학생만 다른 학생에게 빌려주기 가능

** 여벌 체육복을 가져온 학생이 도난당하는 경우, 다른 학생에게 체육복을 빌려줄 수 없음

첫 풀이

function solution(n, lost, reserve) {
    let lostCount = lost.length;
    let reserveCount = 0;
//reserve의 원소가 lost에 모든원소를 돌면서 +=1이 되는 원소를 발견할 경우 찾아야함
    for (let i = 0; i < reserve.length; i++) {
// 여벌 체육복을 도난당했을 경우
        let found = lost.find((data) => data === reserve[i]);
        if (found === undefined) {
            found = lost.find(
                (data) => (data === reserve[i] - 1 || data === reserve[i] + 1)
            );
        }
        if (found !== undefined) {
            let foundIndex = lost.findIndex((data) => data === found);
            lost.splice(foundIndex, 1);
            reserveCount++;
        }
    }
    let result = n - lostCount + reserveCount;
    return result;
}

문제점

// 여벌 체육복을 가져온 학생이 도난당하는 경우의 테스트케이스
n = 5
lost = [2,3,4]
reserve [1,2,3]

문제점 보완 및 코드 깔끔하게 정리해보기

여벌 체육복을 가져온 학생이 도난당하는 경우를 찾아 배열을 정리 + 코드 정리
두 배열간의 비교를 for문을 사용하지 않고 풀어보고자 함 > 이중 filter로 해결

function solution(n, lost, reserve) {
let result;
let distinct_lost = lost.filter((data)=> !reserve.includes(data));
let distinct_reserve = reserve.filter((data)=>!lost.includes(data));
result = n - distinct_lost.filter((lost_el)=>{
let temp = distinct_reserve.find((reserve_el)=> Math.abs(lost_el-reserve_el)<=1);
if(!temp){
    return true;
}
distinct_reserve = distinct_reserve.filter((reserve_el)=> reserve_el !== temp);
}).length;
return result;
}
profile
FE engineer

0개의 댓글