skip to Main Content

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


  1. To generate all possible combinations of strings with special characters, you can use a two-step approach:

    • You need to write a function that can create all the different ways
      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:
      ",,,", ",,.", ",.,", ",..", ".,,", ".,.", "..,", "…".
    • You need to write another function that can insert these combinations of special characters after each character in the string. For
      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..,".

    But there is a problem with this code. It does not make all the
    possible ways to mix the letters and the special characters. It misses
    some ways like "T.est". The problem is that the second function does
    not try to put nothing after a letter in the word. It only tries to
    put one or more special characters, up to a certain limit. To fix
    this, you need to change the second function a little bit. You need to
    add another way to call the function again, without putting any
    special character after the letter.

    For example:

    function generateSpecialChars(specialChars, length) {
      if (length === 0) {
        return [""];
      }
      if (length === 1) {
        return specialChars;
      }
      const combinations = [];
      specialChars.forEach((specialChar) => {
        const subCombinations = generateSpecialChars(specialChars, length - 1);
        subCombinations.forEach((subCombination) => {
          combinations.push(subCombination + specialChar);
        });
      });
      return combinations;
    }
    
    function generateMessages(messages, specialChars, depth) {
      const generatedMessages = [];
      messages.forEach((message) => {
        generateHelper(message, 0, "", specialChars, depth, generatedMessages);
      });
      return generatedMessages;
    }
    
    function generateHelper(message, index, prefix, specialChars, depth, output) {
      if (index >= message.length) {
        output.push(prefix);
        return;
      }
      const char = message[index];
      generateHelper(
        message,
        index + 1,
        prefix + char,
        specialChars,
        depth,
        output
      );
      let repeat = 1;
      while (repeat <= depth) {
        const repeatedChars = generateSpecialChars(specialChars, repeat);
        repeatedChars.forEach((repeatedChar) => {
          generateHelper(
            message,
            index + 1,
            prefix + char + repeatedChar,
            specialChars,
            depth,
            output
          );
        });
        repeat++;
      }
    }
    
    const messages = generateMessages(["Test"], [".", ","], 3);
    console.log(messages)
    Login or Signup to reply.
  2. This can be done with recursion.

    function generateMessages(strs, chars, depth) {
      function gen(str, currDepth) {
        if (!currDepth) return [str];
        const res = currDepth === depth ? [] : gen(str, currDepth - 1);
        for (let i = currDepth === depth; i <= str.length; i++) {
          const left = str.slice(0, i), right = gen(str.slice(i), currDepth - 1);
          for (const c of chars)
            for (const r of right)
              res.push(left + c + r);
        }
        return res;
      }
      return strs.map(s => gen(s, depth));
    }
    console.log(generateMessages(['Test'], ['.', ','], 3));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search