Skip to content

Instantly share code, notes, and snippets.

@uhyo
Created December 8, 2017 08:24
Show Gist options
  • Save uhyo/bebe25dcd18c9483e6a6ecdc23980a7f to your computer and use it in GitHub Desktop.
Save uhyo/bebe25dcd18c9483e6a6ecdc23980a7f to your computer and use it in GitHub Desktop.
Permutation using generator
function* perm(arr, prefix=[]){
if (arr.length <= 1){
yield [...prefix, ...arr];
return;
}
for (const [i, x] of arr.entries()) {
const arr2 = [...arr.slice(0, i), ...arr.slice(i+1)];
yield* perm(arr2, [...prefix, x]);
}
}
function*perm(a,p=[]){
if(a.length===0)
yield p;
else
for(const[i,x]of a.entries())
yield*perm(a.filter((_,j)=>i!==j),[...p,x]);
}
function*perm(a,p=[]){if(a.length===0)yield p; else for(const[i,x]of a.entries())yield*perm(a.filter((_,j)=>i!==j),[...p,x])}
console.log([...perm([1,2,3,4])]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment