Search code examples
javascriptarrayslistiteration

Generate word list variations with fixed and variable words


I'm trying to generate all possible variations of words from a list of words where:

  • the order of the words is fixed
  • some of the words are given
  • some of the words can be one out of many
  • the length of the word list can vary

For example:

one [two|three] four [five|six|seven] [eight|nine] ten

  • "one" is fix at the first position
  • at the second position it's either "two" or "three"
  • "four" is fix at the third position
  • at the fourth position it's either "five", "six" or "seven"
  • at the fifth position it's either "eight", or "nine"
  • "ten" is fix at the sixth position

i am trying to solve this in Javascript and would need an array of all possible strings containing these words.

I've tried a few things to build such an array but got messed up with increasing indexes each time. any help would be greatly appreciated.


Solution

  • try this code.

    const generateCombination = (input) => {
      let words = input.split(' ');
    
      let arr = words.map((element) => element.replaceAll(/\[|]/gm, '').split('|'));
    
      let arCur = arr[0];
      for (let i = 1; i < arr.length; i++) {
        arCur = combine2Arr(arCur, arr[i]);
      }
      return arCur;
    };
    
    const combine2Arr = (ar1, ar2) => {
      let res = [];
      ar1.map((ar1Elem) => {
        ar2.map((ar2Elem) => {
          res.push(ar1Elem + ' ' + ar2Elem);
        });
      });
      return res;
    };
    
    console.log(generateCombination('one [two|three] four [five|six|seven] [eight|nine] ten'));
    

    result

    [
      'one two four five eight ten',
      'one two four five nine ten',
      'one two four six eight ten',
      'one two four six nine ten',
      'one two four seven eight ten',
      'one two four seven nine ten',
      'one three four five eight ten',
      'one three four five nine ten',
      'one three four six eight ten',
      'one three four six nine ten',
      'one three four seven eight ten',
      'one three four seven nine ten'
    ]