์ํ๊ธฐ๋ณธ์ด๋ก / ๊ฒฝ์ฐ์ ์ / ์กฐํฉ
: ์๋ก ๋ค๋ฅธ n๊ฐ์ ์์ ์ค์์ r์ ์ค๋ณต ์์ด ๊ณจ๋ผ ์์์ ์๊ด ์์ด ๋์ด
=> for๋ฌธ๊ณผ ์ฌ๊ทํจ์๋ก ํํ๊ฐ๋ฅํ๋ฉฐ, ์์ ํ์์ ํด๋นํ๋ค.
์์์ฌ์ง
4๊ฐ์ ์ซ์์นด๋์์ 2๊ฐ๋ฅผ ๋ฝ๋ ๊ฒฝ์ฐ
// >> for๋ฌธ์ผ๋ก ๊ตฌํ
let input = [1, 2, 3, 4];
let count = 0;
function combination(arr) {
// for ๋ฌธ ๊ฐ์ => ๋ฝ๋ ๊ฐ์ == r ==> 2
// ์ธ๋ฑ์ค 3, ์ฆ vaule 4๊ฐ ์ค๊ฒ ๋๋ฉด
// j๋ 4๊ฐ ๋๋ค.
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
count++;
console.log(arr[i], arr[j]);
}
}
}
combination(input);
console.log(count);
/*
1 2
1 3
1 4
2 3
2 4
3 4
6
*/
count ๋ณ์๋ ์ด ๋ช๋ฒ์ ๊ฒฝ์ฐ์ ์๊ฐ ์๋์ง ์นด์ดํ
ํ๊ธฐ ์ํ ๋ณ์ ์ด๋ฉฐ, ๋ฝ๋ ๊ฐฏ์๋งํผ for๋ฌธ์ ๊ฐฏ์๊ฐ ๋๋ค.
์ฒ์์๋ ๋ค ๋ฝ์ ์ ์๊ธฐ ๋๋ฌธ์ i++์ ํด์ฃผ๊ณ , j๋ i ์ดํ์ ๊ฐ๋ง ์ ํํ ์ ์๋๋ก ํด์ฃผ์๋ค.
๋ง์ฝ i = 3 (value = 4)์ผ ๊ฒฝ์ฐ, j๋ index = 4๊ฐ ๋์ด ์๋์ ์ผ๋ก for๋ฌธ์ด skip์ฒ๋ฆฌ ๋๋ค. -> ๋ฐ๋ผ์, ์์ธ์ฒ๋ฆฌ๋ฅผ ๋ฐ๋ก ํด์ฃผ์ง ์์
// >> ์ฌ๊ทํจ์๋ก ๊ตฌํ
let Input = [1, 2, 3, 4]; // 4C2
let Output = [];
let Count = 0;
// arr, data : Output์ ์ ์ฅ๋ ๊ฐ,
// s : ์ฌ์ํ๋ ๊ฐ,
// idx : ํ์ฌ ์์น(for loop starting point),
// r : ๋๋๋ ๊ฐ
function combination(arr, data, s, idx, r) {
if (s == r) {
Count++;
console.log(data);
return;
}
// break ํฌ์ธํธ
for (let i = idx; arr.length - i >= r - s; i++) {
data[s] = arr[i];
combination(arr, data, s + 1, i + 1, r);
}
}
combination(Input, Output, 0, 0, 2);
console.log(Count);
/*
[ 1, 2 ]
[ 1, 3 ]
[ 1, 4 ]
[ 2, 3 ]
[ 2, 4 ]
[ 3, 4 ]
6
*/
์ฌ๊ทํจ์์์๋ output์ด๋ผ๋ ๋ณ๋ array๋ฅผ ์ค์ ๋ฝ์ ๊ฒ์ ๋ฐฐ์ด์ ์ ์ฅํ๋ค.
s๊ฐ r๊ณผ ๋์ผํ๋ค๋ฉด, ๋ฉ์ถ๊ฒ ํด์ฃผ๋ break ํฌ์ธํธ๋ฅผ ๋ง๋ค์ด์ค๋ค.
for๋ฌธ : i๋ index๋งํผ ๋๋ฉด์ length์์ -1์ ํ๊ฒ์ด r - s ๋ณด๋ค ํฌ๊ฑฐ๋ ๊ฐ์๋๋ง ์คํ์์ผ์ค๋ค. data ๋ถ๋ถ์๋ arr ๊ฐ์ ๋ณต์ฌํด์ฃผ๊ณ combination์์ ๊ฐ๊ฐ์ ์์๋ค์ ๋งค๊ฐ๋ณ์๋ก ๋ฃ์ด์ฃผ๋ฉฐ, s์ index๋ ํ๋ ์ฆ๊ฐ์์ผ์ค๋ค.