I'm trying to generate all possible variations of words from a list of words where:
For example:
one [two|three] four [five|six|seven] [eight|nine] ten
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.
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'
]