Skip to content

Instantly share code, notes, and snippets.

@bishil06
Created February 25, 2021 05:50
Show Gist options
  • Save bishil06/b013668a1d519bc45c56d636d01a60d9 to your computer and use it in GitHub Desktop.
Save bishil06/b013668a1d519bc45c56d636d01a60d9 to your computer and use it in GitHub Desktop.
JavaScript Array Permutation es2015 generator
function *permutation(arr, size = arr.length) {
yield *permutUntil(arr);
function *permutUntil(list, picked=[]) {
if (list.length === arr.length - size) {
// 원하는 길이만큼 뽑힐때까지 반복
return yield picked;
}
for(let i=0; i<list.length; i++) {
let copiedList = list.slice(); // deep copy
let copiedPicked = picked.slice(); // deep copy
let pick = copiedList.splice(i, 1); // copiedList에서 0 ~ list.length 중 하나를 뽑는다
copiedPicked.push(...pick); // copiedPicked 에 추가
yield *permutUntil(copiedList, copiedPicked); // recursive ([1, 2, 3] []) => ([2, 3] [1]) => ([3] [1, 2]) => ([] [1, 2, 3])
}
}
}
for(const a of permutation([1, 2, 3, 4], 2)) {
console.log(a);
}
/*
[ 1, 2 ]
[ 1, 3 ]
[ 1, 4 ]
[ 2, 1 ]
[ 2, 3 ]
[ 2, 4 ]
[ 3, 1 ]
[ 3, 2 ]
[ 3, 4 ]
[ 4, 1 ]
[ 4, 2 ]
[ 4, 3 ]
*/
console.log([...permutation([1, 2, 3])]);
/*
[
[ 1, 2, 3 ],
[ 1, 3, 2 ],
[ 2, 1, 3 ],
[ 2, 3, 1 ],
[ 3, 1, 2 ],
[ 3, 2, 1 ]
]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment