I’m trying to get all possible combinations of given strings with special chars after each char in the string.
Given:
const messages = generateMessages(['Test'], ['.', ','], 3);
What i have done so far:
function generateMessages(messages, specialChars, depth) {
const generatedMessages = [];
messages.forEach((message) => {
for(let x = 0; x < message.length; x++) {
specialChars.forEach((specialChar) => {
let currentDepth = 1;
while(currentDepth <= depth) {
let temp = '';
temp += message.substring(0, x+1); // I think here is the problem!
temp += generateSpecialChars(specialChar, currentDepth);
temp += message.substring(x +1);
generatedMessages.push(temp);
currentDepth++;
}
})
}
})
return generatedMessages;
}
function generateSpecialChars(char, depth) {
let temp = '';
for (let i = 0; i < depth; i++) {
temp += char;
}
return temp;
}
Current output:
[
'T.est', 'T..est', 'T...est',
'T,est', 'T,,est', 'T,,,est',
'Te.st', 'Te..st', 'Te...st',
'Te,st', 'Te,,st', 'Te,,,st',
'Tes.t', 'Tes..t', 'Tes...t',
'Tes,t', 'Tes,,t', 'Tes,,,t',
'Test.', 'Test..', 'Test...',
'Test,', 'Test,,', 'Test,,,'
]
The output i want:
[
'T.est', 'T..est', 'T...est',
'Te.st', 'T.e.st', 'T..e.st', T...e.st',
'Te..st', 'T.e..st', 'T..e..st', T...e..st',
'Te...st', 'T.e..st', 'T..e...st', T...e...st',
'Tes.t', 'T.es.t', 'T..es.t', T...es.t',
'Te.s.t', 'T.e.s.t', 'T..e.s.t', T...e.s.t',
...
]
I also want to combine the special chars dependend on the depth:
Assume the depth is 3 and we have the special chars [‘,’ and ‘.’]
[
'T.est', 'T..est', 'T...est',
'T.est', 'T..est', 'T..,est',
'T.est', 'T..est', 'T.,,est',
'T.est', 'T..est', 'T,,,est',
'T.est', 'T.,est', 'T,,,est',
'T.est', 'T,,est', 'T,,,est',
'T,est', 'T,,est', 'T,,,est',
...
]
Can anyone help me please?
2
Answers
To generate all possible combinations of strings with special characters, you can use a two-step approach:
to combine the special characters with a given number of times. For
example, if you have two special characters, "," and ".", and you
want to combine them three times, you can get these combinations:
",,,", ",,.", ",.,", ",..", ".,,", ".,.", "..,", "…".
example, if you have the string "Test" and the combination "..,", you can insert it after each character and get "T..,est", "Te..,st",
"Tes..,t", "Test..,".
For example:
This can be done with recursion.