프린터(프로그래머스)

정승옥(seungok)·2020년 12월 22일
0

프로그래머스

목록 보기
24/40
post-thumbnail

문제설명

  • 프린터 인쇄방식
    1) 인쇄 대기목록의 가장 앞에 있는 문서를 꺼냄
    2) 나머지 대기목록에서 꺼낸 문서보다 중요도가 높은 문서가 하나라도 있으면 맨 뒤로 넣음
    3) 그렇지 않으면 꺼낸 문서 인쇄

제한사항

  • 현재 대기목록에는 1개이상 100개이하의 문서가 있음
  • 인쇄 중요도는 1~9로 표현하며 클수록 중요하다는 뜻
  • location은 0이상 현재 대기목록에 있는 작업수 -1이하의 값을 가짐

풀이

function solution(priorities, location) {
    let myPrintLocation = location; // 내 문서의 위치
    let answer = 1; // 결과값
    
    while(true){
        const selectPrint = priorities[0]; // 현재 대기목록의 제일 앞에 있는 문서
        // 선택한 문서보다 중요도가 큰 문서가 하나라도 있으면 true 리턴
        // 선택한 문서를 빼서 다시 제일 뒤로 넣음
        if(priorities.some((print)=>selectPrint<print)){
            priorities.shift();
            priorities.push(selectPrint);
        }
        // 그렇지 않다면 제일 앞에 있는 문서가 내 문서라면 반복문 종료
        // 아니면 대기목록에서 제외하고 결과값 + 1
      	else{
            if(myPrintLocation === 0)
                break;
            priorities.shift();
            ++answer;
        }
        // 0보다 크면 앞으로 한칸 당기고 작으면 제일 뒤로 보냄
        if(myPrintLocation > 0)
            --myPrintLocation;
        else
            myPrintLocation = priorities.length - 1;
    }
    
    return answer;
}

+ 다시 풀었더니 코드가 또 다르네...

function solution(priorities, location) {
	let rank = 0;
	while (true) {
		const printFile = priorities[0];
		if (priorities.some(e => e > printFile)) {
			priorities.shift();
			priorities.push(printFile);
			if (location === 0) location = priorities.length - 1;
			else --location;
		} else {
			++rank;
			if (location === 0) break;
			else {
				--location;
				priorities.shift();
			}
		}
	}

	return rank;
}

체크포인트

  • Math.max(...arr)로 최대값을 비교하여 풀었지만 시간초과
  • some() 메서드를 이용하여 풀어야하는 문제
profile
Front-End Developer 😁

0개의 댓글