728x90
๐ section06 - 6 - ๊ณต์ฃผ๊ตฌํ๊ธฐ
๊ณต์ฃผ ๊ตฌํ๊ธฐ ๋ฌธ์ ๋ ์ด์ ์ ํ์๋ ์์ธํธ์ค ๋ฌธ์ ์ ๋์ผํ๋ค. ์์ธํธ์ค ๋ฌธ์ ๋ ํ(queue)
์๋ฃ๊ตฌ์กฐ๋ฅผ ์ฌ์ฉํ๋ฉด ํ ์ ์๋ค. ์ ์๋๊ป์๋ ์ด๋ ๊ฒ ์ค๋ช
ํด์ฃผ์
จ๋ค.
arr
์length
๊ฐ 1๊ฐ์ผ ๋๊น์ง ๋ฐ๋ณตํ๋ค.for
๋ฌธ์ ์ฌ์ฉํดk-1
๋ฒ ๋๋ฆฐ๋ค.arr[0]
์ ๋งจ ๋ค๋ก ๋ฃ๋๋ค.k
๋ฒ์งธ ์ฌ๋์ด ์ ์ธ๋์ด์ผ ํ๋ฏ๋ก ๋ค์ ๊ฐ์shift()
ํ๋ค.
728x90
// ๊ฐ์ ์ฝ๋
let n = 8;
let k = 3;
console.log(solution(n, k));
function solution(n, k){
let arr = Array.from({length: n}, (v, i) => i+1);
while(arr.length>=2){
for (let i=0; i<k-1; i++) arr.push(arr.shift());
arr.shift();
}
return +arr;
}
// ๋์ ์ฝ๋
let n = 8;
let k = 3;
console.log(solution(n, k));
function solution(n, k) {
let princes = Array.from({ length: n }, (value, idx) => idx + 1);
let cnt = 0;
while (princes.length >= 2) {
if (cnt === k - 1) princes.splice(0, 1), (cnt = 0);
else princes.push(princes.shift()), cnt++;
}
return +princes;
}
// ๋์ ์ฝ๋2
let n = 8;
let k = 3;
console.log(solution(n, k));
function solution(n, k) {
let princes = Array.from({ length: n }, (value, idx) => idx + 1);
let cnt = 0;
while (princes.length >= 2) {
cnt = (cnt + k - 1) % princes.length;
princes.splice(cnt, 1);
}
return +princes;
}
๋ฐ์ํ
๋๊ธ