일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- 파이썬
- 너비 우선 탐색
- BASIC
- 딕셔너리
- 그래프 탐색
- level2
- 프로그래머스
- 스택
- 구현
- 브루트포스 알고리즘
- DFS
- DP
- 알고리즘
- BFS
- CSS
- lv2
- 프로그래머스스쿨
- 백준
- JavaScript
- programmers
- 웹 프론트엔드
- 다이나믹 프로그래밍
- 그래프이론
- 자바스크립트
- web
- 그리디 알고리즘
- 자료구조
- 문자열
- 정렬
- 그래프 이론
Archives
- Today
- Total
DevLog:-)
[프로그래머스][Javascript]프로세스 본문
반응형
문제
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
코드
function solution(priorities, location) {
let q1 = [...priorities];
let q2 =[];
let p,l;
let count =0;
for (let i in q1){
q2.push(parseInt(i));}
while(q1){
p = q1.shift();
l = q2.shift();
if(Math.max(...q1)>p){
q1.push(p);
q2.push(l);}
else{
count++;
if(l==location){
return count;
}
}
}
}
풀이
큐를 구현하는 문제이다.
배열의 push와 shift함수를 이용해서 큐의 인큐(enqueue)와 디큐(dequeue)를 구현했다.
큐에 담아야 할 요소가 프로세스를 구별하는 값과 각각의 우선순위가 있다.
하나의 큐에 두 개의 요소를 넣기보단 두 배열을 이용해 각각의 값을 순서대로 넣었다.
두 개의 배열을 사용하는 방법도 있지만 더 간단하고 보기 좋은 방법이 있다.
바로 object를 사용하는 것이다.
📖다른 풀이
function solution(priorities, location) {
var arr = priorities.map((priority, index) => {
return {
index: index, priority: priority
};
});
//object로 index와 priority 저장
var queue = [];
while(arr.length > 0) {
var firstEle = arr.shift();
var hasHighPriority = arr.some(ele => ele.priority > firstEle.priority);
//arr.some(조건) firstEle보다 우선순위가 더 큰게 있으면 True
if (hasHighPriority) {
arr.push(firstEle); //다시 넣기
} else {
queue.push(firstEle); //실행 순서데로 넣어짐
}
}
return queue.findIndex(queueEle => queueEle.index === location) + 1;
//구하고자 하는 프로세스의 순서 반환
}
✅checkpoint!
arr_new = [...arr] | 기존의 배열(arr)을 새로운 배열(new_arr)에 복사하는 법(얕은 복사) |
Math.max(...arr) | 배열 안에 값 중에 큰 값 반환 |
arr.some(함수) | 조건에 맞는 값이 있는지 여부(boolean) 반환 |
-arr.some(callback) -반환: true, false ex) arr =[1,2,3,4,5] arr.some((e)=>e===2); //true반환 |
|
findIndex(함수) | 인자로 받은 판별 함수를 만족하는 첫 번째 식별자를 반환 |
-arr.findIndex(callback) -반환: index, 없다면 -1 -callback(element, index, array) -원하는 요소를 찾자마자 메서드를 종료 ex) arr =[1,2,3,4,5] let result = arr.findIndex((element, index, arr) => element === 2); //1반환 let result2 = arr.findIndex((e) => e > 4); //4반환 |
💡idea
큐(Queue)란? | - 스택과 마찬가지로 데이터를 일시적으로 쌓아 놓은 자료구조 - 선입선출(FIFO, LILO)의 구조 |
2023.9.25 update
큐를 shift()를 통해 구현하게 되면 선형시간이 발생해 추천하지 않는다.
shift를 사용하지 않고 작성한 코드
class Queue {
constructor() {
this.queue = [];
this.front = 0;
this.rear = 0;
}
enqueue(value) {
this.queue[this.rear++] = value;
}
dequeue() {
const value = this.queue[this.front];
delete this.queue[this.front];
this.front += 1;
return value;
}
peek() {
return this.queue[this.front];
}
size() {
return this.rear - this.front;
}
hasHigherPriority(priority) {
for (let i = this.front; i < this.rear; i++) {
if (this.queue[i].priority > priority) {
return true;
}
}
return false;
}
}
function solution(priorities, location) {
var answer = 0;
const q = new Queue();
for (let i in priorities) {
q.enqueue({ priority: priorities[i], index: i });
}
while (q.size!==0) {
const currentDoc = q.dequeue();
if (q.hasHigherPriority(currentDoc.priority)) {
q.enqueue(currentDoc);
} else {
answer++;
if (currentDoc.index == location) {
break;
}
}
}
return answer;
}
반응형
'알고리즘 > 프로그래머스' 카테고리의 다른 글
[프로그래머스][Javascript]구명보트 (0) | 2023.08.27 |
---|---|
[프로그래머스][Javascript]카펫 (0) | 2023.08.21 |
[프로그래머스][JavaScript]JadenCase 문자열 만들기 (0) | 2023.08.13 |
[프로그래머스][Javascript]모음사전 (0) | 2023.08.05 |
[프로그래머스][Javascript]멀리뛰기 (0) | 2023.08.04 |