Skip to content

Instantly share code, notes, and snippets.

@Beraliv
Created November 3, 2019 19:26
Show Gist options
  • Save Beraliv/803f3038ff47d70ed569162362979144 to your computer and use it in GitHub Desktop.
Save Beraliv/803f3038ff47d70ed569162362979144 to your computer and use it in GitHub Desktop.
Find all permutations for a specified string
/**
* Traverse permutation to add new letter to every new position
*
* @example
* generateNextPermutation(['a','b'],'c')
* // => [['c','a','b'],['a','c','b'],['a','b','c']]
*/
function generateNextPermutation(permutation, ch) {
const destination = [];
for (let i = 0; i <= permutation.length; i++) {
const nextPermutation = permutation.slice();
nextPermutation.splice(i, 0, ch);
destination.push(nextPermutation);
}
return destination;
}
/**
* Traverse over all permutations to add new letter to every new position in every permutation
*
* @example
* generateNextPermutations([['a','b'],['b','a']],'c')
* // => generateNextPermutation(['a','b'],'c')
* // => generateNextPermutation(['b','a'],'c')
* // => [['c','a','b'],['a','c','b'],['a','b','c'],['c','b','a'],['b','c','a'],['b','a','c']]
*/
function generateNextPermutations(permutations, ch) {
const nextPermutations = [];
for (let j = 0; j < permutations.length; j++) {
nextPermutations.push(...generateNextPermutation(permutations[j], ch));
}
return nextPermutations;
}
/**
* Generate permutations for letters within the specified string
*
* @example
* perm('abc')
* // => generateNextPermutations([['a']],'b')
* // => generateNextPermutations([['a','b'],['b','a']],'c')
* // => [['c','a','b'],['a','c','b'],['a','b','c'],['c','b','a'],['b','c','a'],['b','a','c']]
*/
function perms(str) {
let permutations = [[str[0]]];
for (let i = 1; i < str.length; i++) {
permutations = generateNextPermutations(permutations, str[i]);
}
return permutations;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment