Created
December 8, 2017 08:24
-
-
Save uhyo/bebe25dcd18c9483e6a6ecdc23980a7f to your computer and use it in GitHub Desktop.
Permutation using generator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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