728x90
문제
요세푸스 문제는 다음과 같다.
1번부터 N번까지 N명의 사람이 원을 이루면서 앉아있고, 양의 정수 K(≤ N)가 주어진다. 이제 순서대로 K번째 사람을 제거한다. 한 사람이 제거되면 남은 사람들로 이루어진 원을 따라 이 과정을 계속해 나간다. 이 과정은 N명의 사람이 모두 제거될 때까지 계속된다. 원에서 사람들이 제거되는 순서를 (N, K)-요세푸스 순열이라고 한다. 예를 들어 (7, 3)-요세푸스 순열은 <3, 6, 2, 7, 5, 1, 4>이다.
N과 K가 주어지면 (N, K)-요세푸스 순열을 구하는 프로그램을 작성하시오.
입력
첫째 줄에 N과 K가 빈 칸을 사이에 두고 순서대로 주어진다. (1 ≤ K ≤ N ≤ 5,000)
출력
예제와 같이 요세푸스 순열을 출력한다.
예제 입력 1
7 3
예제 출력 1
<3, 6, 2, 7, 5, 1, 4>
풀이
1..input[0]까지의 수를 배열로 담아서 queue를 만든다.
queue 클래스 내에서 input[1] - 1 만큼 queue에 맨 앞에 있는 값을 맨 뒤로 보내고,
queue의 맨 앞의 값이 input[1]과 같아지면 shift를 해서 result 배열에 담는다.
그렇게 해서 result 배열을 완성시킨다.

전체 코드
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require("fs"); | |
const input = (process.platform === "linux" | |
? fs.readFileSync("/dev/stdin").toString() | |
: `3 1` | |
) | |
.split(" ") | |
.map((x) => +x); | |
class Queue { | |
// 1..input[0]만큼의 배열 생성 | |
constructor(len, x) { | |
this._arr = []; | |
this._len = len; | |
this._x = x; | |
for (let i = 1; i <= this._len; i++) { | |
this._arr.push(i); | |
} | |
} | |
size() { | |
return this._arr.length; | |
} | |
// 맨 앞에 있는 수 pop | |
fpop() { | |
return this._arr.shift(); | |
} | |
// input[1] - 1 만큼 앞에 있는 수를 뒤로 보냄 | |
goback() { | |
let x = this._x - 1; | |
while (x > 0) { | |
let f = this._arr.shift(); | |
this._arr.push(f); | |
x--; | |
} | |
} | |
} | |
const queue = new Queue(input[0], input[1]); | |
let result = []; | |
let len = queue.size(); | |
// queue의 length가 0 이될때까지 goback()과 fpop() | |
while (len > 0) { | |
queue.goback(); | |
result.push(queue.fpop()); | |
len--; | |
} | |
// 결과 값 저장후 print | |
console.log(`<${result.join(", ")}>`); |
반응형
'개발👩💻 > 알고리즘' 카테고리의 다른 글
백준 js 17413: 문자열 뒤집기 2 (0) | 2021.05.02 |
---|---|
백준 js 10866: 덱 (0) | 2021.05.01 |
백준 js 10845: 큐 (0) | 2021.04.30 |
백준 js 1406: 에디터 (0) | 2021.04.30 |
백준 js 1874: 스택 수열 (0) | 2021.04.30 |