Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript – Get all unique permutations of a string (special case)

Given a string like "this is a search with spaces", I want to return all permutations of that string where the spaces are replaced with a dash. For example, this is the result that I want:

["this-is-a-search-with-spaces"]
["this-is-a-search-with", "spaces"]
["this", "is-a-search-with-spaces"]
["this-is", "a-search-with-spaces"]
["this-is-a-search", "with-spaces"]
["this-is-a", "search-with-spaces"]
…and so on.

I can do half of this, but the problem is that it matches ["query1-query2", "query3"] but not the opposite way around like ["query1", "query2-query3"].

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This is my current code:

const sliced = query.split(/ +/g)
let permutations = []
for (let i = 1; i <= sliced.length; i++) {
  let permuteArr = []
  for (let j = 0; j < sliced.length; j+=i) {
    permuteArr.push(sliced.slice(j, j+i).join("-"))
  }
  permutations.push(permuteArr)
}

Thanks for helping me.

>Solution :

Here is a recursive generator that yields the combinations:

function permutations(query) {
    
    function* iterRecur(sliced) {
        if (sliced.length == 1) return yield sliced;
        for (const result of iterRecur(sliced.slice(1))) {
            yield [sliced[0] + "-" + result[0], ...result.slice(1)];
            yield [sliced[0], ...result];
        }
    }

    const sliced = query.split(/ +/g);
    return [...iterRecur(sliced)];
}

console.log(permutations("this is a test"));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading