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

[ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ(JavaScript) ] section04 - 3 - ๋ฉ˜ํ† ๋ง

by YWTechIT 2021. 8. 22.
728x90

๐Ÿ“ section04 - 3 - ๋ฉ˜ํ† ๋ง(bruteForce)

์กฐ๊ธˆ ์–ด๋ ค์šด ๋ฌธ์ œ์˜€๋‹ค. bruteForce๋กœ ํ’€์–ด์•ผ ํ•˜๋Š” ๊ฒƒ์€ ์•Œ๊ณ  ์žˆ์—ˆ์ง€๋งŒ, ์–ด๋–ค ํ๋ฆ„์œผ๋กœ ๋ฌธ์ œ๋ฅผ ํ’€์–ด์•ผ ํ• ์ง€ ๊ณ ๋ฏผ์ด ๋งŽ์•˜๋‹ค. ๊ฐ•์˜๋ฅผ ๋ดค๋Š”๋ฐ๋„ ์ดํ•ด๊ฐ€ ์ž˜ ์•ˆ ๋ผ์„œ ๋ณต์Šต์„ ์—ฌ๋Ÿฌ ๋ฒˆ ํ–ˆ๋‹ค.

 

๊ฒฐ๊ณผ์ ์œผ๋กœ ์ด ๋ฌธ์ œ์˜ ํ•ต์‹ฌ์€ n๋ช…์˜ ํ•™์ƒ์ด ๊ฐ๊ฐ์˜ ๊ฒฝ์šฐ์— m๋ฒˆ์˜ ์ˆ˜ํ•™ ์„ฑ์  ๋ชจ๋‘ mento์™€ mentee๊ฐ€ ๋  ์ˆ˜ ์žˆ๋Š” ์กฐ๊ฑด์ด ๋งž๋Š”์ง€ ์ฐพ์•„์•ผ ํ•˜๊ณ , ๊ทธ ์•ˆ์—์„œ ์ˆ˜ํ•™ ๋“ฑ์ˆ˜๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” idx๋ฅผ ๊ณ ๋ คํ•ด์„œ mentoIdx < menteeIdx์ธ ์กฐ๊ฑด์„ ์ฐพ์„ ์ˆ˜ ์žˆ๋Š”์ง€ ๋ฌผ์–ด๋ณด๋Š” ๋ฌธ์ œ์ธ ๊ฒƒ ๊ฐ™๋‹ค. ๋˜, mento์™€ mentee๋Š” ๊ฐ™์€ ํ•™์ƒ์ผ ๋•Œ๋Š” ์„ฑ๋ฆฝํ•˜์ง€ ์•Š์Œ์„ ์•Œ์•„์•ผ ํ•œ๋‹ค.

 

๊ฐ•์˜์—์„œ 4 ์ค‘๋ฐ˜ ๋ณต๋ฌธ์œผ๋กœ ํ’€์—ˆ๋Š”๋ฐ, ๋ฐ˜๋ณต๋ฌธ์˜ ๊ฐœ์ˆ˜๊ฐ€ ๋งŽ๋‹ค ๋ณด๋‹ˆ๊นŒ ํ—ท๊ฐˆ๋ ค์„œ ์ˆ˜ํ•™ ์„ฑ์ ์ด m๊ฐœ๊ฐ€ ์•„๋‹Œ ๋”ฑ 1๊ฐœ๋งŒ ์ฃผ์–ด์กŒ์„ ๋•Œ๋ฅผ ๊ฐ€์ •ํ•˜๊ณ  ํ’€์–ด๋ดค๋‹ค. ๋‹ค์Œ์˜ ์‚ฌ์ง„์ฒ˜๋Ÿผ ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ๋ชจ๋‘ ๊ตฌํ•ด๋ณด๊ณ  ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•˜๋‹ˆ๊นŒ ์กฐ๊ธˆ ์ดํ•ด๊ฐ€ ๋๋‹ค.

 

 

728x90
let arr = [3, 4, 1, 2];
let n = 4;
let m = 1;
let cnt = 0;

for (let x = 1; x <= n; x++) {
  for (let y = 1; y <= n; y++) {
    let mentoIdx = menteeIdx = 0;
    for (let i = 0; i < n; i++) {
      if (x === y) continue;
      if (arr[i] === x) mentoIdx = i;
      if (arr[i] === y) menteeIdx = i;
    }
    if (mentoIdx < menteeIdx) {
        cnt++; 
        console.log(x, y);
    }
  }
}
console.log(cnt);
๐Ÿ‘‰๐Ÿฝ 
1 2
3 1
3 2
3 4
4 1
4 2

6

 

์ˆ˜ํ•™ ์„ฑ์ ์— 2์ฐจ์› ๋ฐฐ์—ด์ด ๋“ค์–ด๊ฐ”์„ ๋•Œ๋„ ์œ„์—์„œ ์ž‘์„ฑํ•œ ์ฝ”๋“œ์—์„œ ํฌ๊ฒŒ ๋ฒ—์–ด๋‚˜์ง€ ์•Š๋Š”๋‹ค. ๋‹ค๋งŒ, mento, mentee์˜ ๊ด€๊ณ„๊ฐ€ ์„ฑ๋ฆฝํ•˜๋ ค๋ฉด ๋ชจ๋“  ์ˆ˜ํ•™ ์„ฑ์ ์—์„œ mento๊ฐ€ ๋” ์•ž์„œ์•ผ ํ•˜๋ฏ€๋กœ cnt๊ฐ€ m๊ณผ ๋™์ผํ•˜๋‹ค๋Š” ์กฐ๊ฑด์„ ๊ฑธ์–ด์ค˜์•ผ ํ•œ๋‹ค. ์ „์ฒด ์ฝ”๋“œ๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค.

 

let arr = [[3, 4, 1, 2], [4, 3, 2, 1], [3, 1, 4, 2]];
let n = 4;
let m = 3;

console.log(solution(n, m, arr));

function solution(n, m, arr){
    let ans = 0;
    for (let x=1; x<=n; x++){
        for (let y=1; y<=n; y++){
            let cnt = 0;
            for (let i=0; i<m; i++){
                let mento = mentee = 0;
                for (let j=0; j<n; j++){
                    if (x===y) continue;
                    if (arr[i][j] === x) mento = j;
                    if (arr[i][j] === y) mentee = j;  
                }
                if (mento < mentee) cnt++;
            }
            if (cnt === m) ans++;
        }
    }
    return ans;
}
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€