๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm/์ธํ”„๋Ÿฐ(inflearn)

[ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ(JavaScript) ] section06 - 6 - ๊ณต์ฃผ๊ตฌํ•˜๊ธฐ

by YWTechIT 2021. 9. 2.
728x90

๐Ÿ“ section06 - 6 - ๊ณต์ฃผ๊ตฌํ•˜๊ธฐ

๊ณต์ฃผ ๊ตฌํ•˜๊ธฐ ๋ฌธ์ œ๋Š” ์ด์ „์— ํ’€์—ˆ๋˜ ์š”์„ธํ‘ธ์Šค ๋ฌธ์ œ์™€ ๋™์ผํ•˜๋‹ค. ์š”์„ธํ‘ธ์Šค ๋ฌธ์ œ๋Š” ํ(queue) ์ž๋ฃŒ๊ตฌ์กฐ๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ํ’€ ์ˆ˜ ์žˆ๋‹ค. ์„ ์ƒ๋‹˜๊ป˜์„œ๋Š” ์ด๋ ‡๊ฒŒ ์„ค๋ช…ํ•ด์ฃผ์…จ๋‹ค.

 

  1. arr์— length๊ฐ€ 1๊ฐœ์ผ ๋•Œ๊นŒ์ง€ ๋ฐ˜๋ณตํ•œ๋‹ค.
  2. for๋ฌธ์„ ์‚ฌ์šฉํ•ด k-1๋ฒˆ ๋Œ๋ฆฐ๋‹ค. arr[0]์„ ๋งจ ๋’ค๋กœ ๋„ฃ๋Š”๋‹ค.
  3. 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;
}
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€