Advertisement
Guest User

Untitled

a guest
May 9th, 2018
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Global permutations array for ease-of-use by functions.
  2. let permutations = [];
  3.  
  4. // Separate from getPermutations because this part gets recursively called.
  5. const getPermutationsInner = ( items, wipPermutation = [] ) => {
  6.  
  7.     items.forEach( ( item, index ) => {
  8.  
  9.         let wipPerm = wipPermutation.concat( item );
  10.  
  11.         // Clone items via slice().
  12.         const otherItems = items.slice();
  13.  
  14.         // splice() modifies arrays, unlike slice().
  15.         otherItems.splice( index, 1 );
  16.  
  17.         if ( otherItems.length === 0 )
  18.             permutations.push( wipPerm );
  19.         else
  20.             getPermutationsInner( otherItems, wipPerm );
  21.  
  22.     } );
  23.  
  24. };
  25.  
  26. // Gets all permutations of an array of items. Assumes every item is unique.
  27. const getPermutations = items => {
  28.  
  29.     getPermutationsInner( items );
  30.  
  31.     // Clone current value of permutations.
  32.     const returnedPermutations = permutations;
  33.  
  34.     // Reset permutations variable so it is empty when the function is called again.
  35.     permutations = [];
  36.  
  37.     return returnedPermutations;
  38.  
  39. };
  40.  
  41. // Gets all permutations of the characters of a string. Assumes every character is unique.
  42. const getPermutationsOfString = str =>
  43.     getPermutations( str.split( '' ) ).map( permutation => permutation.join( '' ) );
  44.  
  45. const permAlone = str => {
  46.  
  47.     // Get all possible permutations of the string.
  48.     const permutations = getPermutationsOfString( str );
  49.  
  50.     // Filter out all permutations that have 2 or more identical consecutive characters.
  51.     const permutationsWithoutRepeatedChars = permutations.filter(
  52.         permutation => permutation.match( /(.)(?=\1)/g ) === null ? true : false
  53.     );
  54.  
  55.     return permutationsWithoutRepeatedChars.length;
  56.  
  57. };
  58.  
  59. permAlone( 'aab' );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement