Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

151
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda