Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

153
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda