Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

141
Views
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"].

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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"));

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!