
17. Deck of Cards
Sunhyup Lee. (2024). To be a successful candidate for the coding test. goldenrabbit. p.215.
Problem solving
1. Queue를 이용하여 풀기

Queue solving
Jay Tak
class Queue {
items = [];
front = 0;
rear = 0;
constructor(array) {
this.items = array; // 초기 배열로 큐를 생성
this.rear = array.length; // rear는 배열의 끝을 가리킴
}
push(item) {
this.items.push(item); // 큐의 끝에 아이템 추가
this.rear++;
}
pop() {
return this.items[this.front++]; // front에서 아이템 제거 후 포인터 이동
}
first() {
return this.items[this.front]; // 큐의 front에 있는 아이템 반환
}
isEmpty() {
return this.front === this.rear; // front와 rear가 같으면 큐가 비어 있음
}
}
function solution(cards1, cards2, goal) {
cards1 = new Queue(cards1); // cards1을 큐로 변환
cards2 = new Queue(cards2); // cards2를 큐로 변환
goal = new Queue(goal); // goal을 큐로 변환
while (!goal.isEmpty()) {
// goal이 빌 때까지 반복
if (!cards1.isEmpty() && cards1.first() === goal.first()) {
cards1.pop(); // cards1의 첫 번째 단어를 사용
goal.pop(); // goal의 첫 번째 단어 제거
} else if (!cards2.isEmpty() && cards2.first() === goal.first()) {
cards2.pop(); // cards2의 첫 번째 단어를 사용
goal.pop(); // goal의 첫 번째 단어 제거
} else {
break; // cards1과 cards2 모두에서 사용할 단어를 찾을 수 없는 경우
}
}
return goal.isEmpty() ? "Yes" : "No"; // goal이 비어 있으면 "Yes", 아니면 "No"
}