Skip to content

Instantly share code, notes, and snippets.

@robbywashere-zz
Created March 24, 2018 12:17
Show Gist options
  • Save robbywashere-zz/f8c4794a19eff77e14c8271676268cd9 to your computer and use it in GitHub Desktop.
Save robbywashere-zz/f8c4794a19eff77e14c8271676268cd9 to your computer and use it in GitHub Desktop.
Permutations the lazier way (Sorry Heap's Algo)
function splice(arr, pos) {
let nArr = Array.from(arr);
return [ nArr.splice(pos,1), nArr ];
}
function p(arr, result = [], chr = []){
if (arr.length === 1) result.push(chr.concat(arr).join(''));
for (let i = 0; i <= arr.length-1; i++) {
const [c, n] = splice(arr,i);
p(n,result,chr.concat(c));
}
return result;
}
const result = p('abcdefg'.split(''));
console.log(JSON.stringify(result,null,2));
console.log(result.length)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment