Search code examples
javascriptpermutation

Permutation in JavaScript


Here is my problem:

For a given sentence, find occurrences of the given character set. Pick filtered words and generate permutations. (SENTENCE AND CHARACTER SET ONLY CAN HAVE UPPERCASE LETTERS)

Show selected words & permutations

Example:

Inputs

sentence = "THIS IS AN ISSUE FROM JOHN" 
word = "IS"

Output:

{ 
  words: ["THIS", "IS", "ISSUE"], 
  permutations: [["THIS","IS","ISSUE"], ["IS","THIS","ISSUE"], ["ISSUE","THIS","IS"], ["THIS","ISSUE","IS"], ["IS","ISSUE","THIS"], ["ISSUE","IS","THIS"]] 
}

And the following criteria should be fulfilled:

  1. Return type should be an object.

  2. getPermutations("THIS IS AN ISSUE FROM GIHAN", "IS")

    Should return:

    { 
      "word": ["THIS","IS","ISSUE"], 
      "permutations": [["THIS","IS","ISSUE"], ["IS","THIS","ISSUE"], ["ISSUE", "THIS", "IS"], ["THIS", "ISSUE", "IS"], ["IS", "ISSUE", "THIS"], ["ISSUE","IS","THIS"]]
    }
    
  3. Answer should be valid for any given input.

Here is my code:

function getPermutations(sentence, word) {
  var words = sentence.split(" ");
  var x = words[0] +" "+ words[1] +" "+ words[3];
  var inputArray = x.split(" ");
  var permutations = inputArray.reduce(function permute(res, item, key, arr) {
    return res.concat(arr.length > 1 && arr.slice(0, key).concat(arr.slice(key + 1)).reduce(permute, []).map(function(perm) { return [item].concat(perm); }) || item);

}, []);

  var output = { words: words,permutations :  permutations}; 


  return output;
}

console.log(getPermutations("THIS IS AN ISSUE FROM JOHN", "IS"));

there is some error so it confusing with this. Any suggestion please?


Solution

  • Use a regex (/\w*IS\w*/g) and match to extract the words containing the characters you specify. Use a Set to remove the duplicates, then generate the permutations of that array with reduce, flat, map and filter:

    function permutations(arr) {
      return (arr.length === 1) ? arr : arr.reduce((acc, x, i) => {
        const remaining = [...new Set(arr)].filter((y, j) => i !== j);
        return [...acc, ...permutations(remaining).map(a => [x, a].flat())];
      }, []);
    }
    
    function getPermutations(str, word) {
      const words = [...new Set(
        (word && (str || '').match(new RegExp(`\\w*${word}\\w*`, 'g'))) || [])
      ];
      return { words, permutations: permutations(words) };
    }
    
    console.log(getPermutations('THIS IS AN ISSUE FROM JOHN', 'IS'));
    console.log(getPermutations('THIS IS', 'IS'));
    console.log(getPermutations('', 'IS'));
    console.log(getPermutations(null, 'IS'));
    console.log(getPermutations('', ''));
    console.log(getPermutations('', null));