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

150
Views
Javascript - Getting all possible k-length strings from given list of characters using generator

I want to get all k-length strings from given list of characters. I already wrote recursive function and it works well. But my generator version doesn't work at all. How can I fix my second function? Many thanks.

// recursive version
function product_rec(arr, k) {
    if (k == 1) return arr;
    let res = [];
    for (const elem of arr) {
        for (const s of product_rec(arr, k - 1)) {
            res.push(elem + s);
        }
    }
    return res;
}

var p = product_rec(['0', '1'], 2);
console.log(p);  // [ '00', '01', '10', '11' ]


// RangeError: Maximum call stack size exceeded
function* product_rec_gen(arr, k, result) {
    if (k == 1) {
        for (const elem of arr) yield elem;
    }
    for (const elem of arr) {  
        for (const s of product_rec_gen(arr, k - 1)) {
            yield elem + s;
        }
    }
}

var p = product_rec_gen(['0', '1'], 2);
// RangeError: Maximum call stack size exceeded 
for (const e of p){
    console.log(e);
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Iterate each element of the input array no matter it's length, handling the k==1 case inside the loop. Form the remainder array for each element and combine that element with the recursive call using that remainder...

function* product_rec(arr, k) {
  for (let i = 0; i < arr.length; i++) {
    if (k === 1) {
      yield [arr[i]];
    } else {
      const rest = product_rec(arr.slice(i+1), k-1);
      for (let el of rest) {
        yield [arr[i], ...el];
      }
    }
  }
}

const generator = product_rec(['a', 'b', 'c', 'd'], 2);

console.log(generator.next().value)
console.log(generator.next().value)
console.log(generator.next().value)
console.log(generator.next().value)
console.log(generator.next().value)
console.log(generator.next().value)

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!