Algorithm Problem/JavaScript

[JavaScript] 프로그래머스 - 체육복

deo2kim 2020. 7. 25. 02:58
반응형

문제 해결

1. 체육복을 잃어버린 학생이 여벌을 가지고 있는 경우를 제외 한다.

2. 체육복을 잃어버린 학생으로 for 문을 돌리며

 (1) 학생보다 이전 번호의 학생이 여벌을 가지고 있다면 그냥 빌린다.

 (2) 학생보다 이전 번호의 학생이 여벌을 가지고 있지 않고, 다음 사람이 가지고 있다면 빌리고, 여벌을 가지고 있는 학생을 지운다.

 (3) 양쪽 모두 없으면 넘어간다.

 (4) 체육복을 빌릴 때마다 카운트를 센다.

 

☔ 깜빡하고 블로그를 쓰지 못했다... 늦게라도 쓴다 ㅠ

오늘은 filter를 알아보자.

 

🚐 filter

이 메소드는 배열에서 특정 조건을 만족하는 값(들)을 모아 다시 배열로 만드는 작업이다.

var arr = [1,2,3,4,5,6,7,8,9]
var newArr = arr.filter( number => number > 5 )
console.log(newArr)  // [ 6, 7, 8, 9 ]

 

소스 코드

function solution(n, lost, reserve) {  
  const noDupleLost = lost.filter( (s) => (reserve.indexOf(s) === -1))
  const noDupleReserve = reserve.filter( (s) => (lost.indexOf(s) === -1))
  
  noDupleLost.sort()
  var answer = n-noDupleLost.length
  noDupleLost.forEach(lostStudent => {

    if (noDupleReserve.indexOf(lostStudent-1) >= 0) {
      answer ++

    } else if (noDupleReserve.indexOf(lostStudent+1) >= 0) {
        answer ++
        var reserveStudent = noDupleReserve.indexOf(lostStudent+1)
        noDupleReserve.splice(reserveStudent, 1)
    }
  })
  return answer;
}

console.log(solution(5, [2,5], [1,3,5]));
console.log(solution(5, [2,4], [3]));
console.log(solution(3, [3], 	[1]));

console.log(solution(5, [2,3], [3,4]))  // 4

 

출처: 프로그래머스

문제: https://programmers.co.kr/learn/courses/30/lessons/42862?language=javascript

 

코딩테스트 연습 - 체육복

점심시간에 도둑이 들어, 일부 학생이 체육복을 도난당했습니다. 다행히 여벌 체육복이 있는 학생이 이들에게 체육복을 빌려주려 합니다. 학생들의 번호는 체격 순으로 매겨져 있어, 바로 앞번�

programmers.co.kr

 

반응형