Home > Back-end >  Javascript - Getting all possible k-length strings from given list of characters using generator
Javascript - Getting all possible k-length strings from given list of characters using generator

Time:05-11

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

CodePudding user response:

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)

  • Related