Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Global permutations array for ease-of-use by functions.
- let permutations = [];
- // Separate from getPermutations because this part gets recursively called.
- const getPermutationsInner = ( items, wipPermutation = [] ) => {
- items.forEach( ( item, index ) => {
- let wipPerm = wipPermutation.concat( item );
- // Clone items via slice().
- const otherItems = items.slice();
- // splice() modifies arrays, unlike slice().
- otherItems.splice( index, 1 );
- if ( otherItems.length === 0 )
- permutations.push( wipPerm );
- else
- getPermutationsInner( otherItems, wipPerm );
- } );
- };
- // Gets all permutations of an array of items. Assumes every item is unique.
- const getPermutations = items => {
- getPermutationsInner( items );
- // Clone current value of permutations.
- const returnedPermutations = permutations;
- // Reset permutations variable so it is empty when the function is called again.
- permutations = [];
- return returnedPermutations;
- };
- // Gets all permutations of the characters of a string. Assumes every character is unique.
- const getPermutationsOfString = str =>
- getPermutations( str.split( '' ) ).map( permutation => permutation.join( '' ) );
- const permAlone = str => {
- // Get all possible permutations of the string.
- const permutations = getPermutationsOfString( str );
- // Filter out all permutations that have 2 or more identical consecutive characters.
- const permutationsWithoutRepeatedChars = permutations.filter(
- permutation => permutation.match( /(.)(?=\1)/g ) === null ? true : false
- );
- return permutationsWithoutRepeatedChars.length;
- };
- permAlone( 'aab' );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement