Skip to content

์ˆœ์—ด (Permutation) โ€‹

์ˆœ์—ด์ด๋ž€, ์„œ๋กœ ๋‹ค๋ฅธ N๊ฐœ ์ค‘์—์„œ R๊ฐœ๋ฅผ ์„ ํƒํ•˜๋Š” ๊ฒฝ์šฐ (์ˆœ์„œ ์ค‘์š”๐Ÿ‘Œ )

์ˆœ์—ด ์ˆ˜์‹

swap์„ ์ด์šฉํ•œ ์ˆœ์—ด ๋งŒ๋“ค๊ธฐ โ€‹

์ˆœ์—ด swap ๊ฐ€์ด๋“œ

javascript
/**
 *
 * @param {array} array
 * @param {number} deep
 * @param {number} target
 */
const permutation = (array, res = [], target = array.length, deep = 0) => {
	if (deep === target) {
		res.push(array.slice(0, target));
		return;
	}
	for (let index = deep; index < array.length; index++) {
		swap(array, deep, index);
		permutation(array, res, target, deep + 1);
		swap(array, deep, index);
	}
};

const swap = (array, a, b) => {
	let tmp = array[a];
	array[a] = array[b];
	array[b] = tmp;
};

const getPermutationList = (array, target) => {
	let res = [];
	permutation(array, res, target);
	return res;
};

const array = Array(3)
	.fill()
	.map((_, i) => i + 1);
console.log(getPermutationList(array));

/* --------------------------------------------------
[ 1, 2, 3 ]
[ 1, 3, 2 ]
[ 2, 1, 3 ]
[ 2, 3, 1 ]
[ 3, 2, 1 ]
[ 3, 1, 2 ]
*/