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

145
Visualizações
in this combination recursive, is it always return correct answer?

Below is widely known combination function.

function getCombination(arr,selectNumber){
    const result = [];
        if(selectNumber == 1) {
            return arr.map(el => [el])
    };

    arr.forEach((fixed, index, array)=>{

        const rest = array.slice(index+1);
        const combinations = getCombination(rest, selectNumber - 1);
        const attached = combinations.map((el => [fixed,...el]));

        result.push(...attached);

    });

    return result;
};

I traced code and found some useless calculations when (index == array.length-1) in forEach segment. so I added "if()" in that. is it always return correct results?

function getCombination(arr,selectNumber){
    const result = [];
        if(selectNumber == 1) {
            return arr.map(el => [el])
    };

    arr.forEach((fixed, index, array)=>{

        if(index == array.length-1) return; /* I added this line */

        const rest = array.slice(index+1);
        const combinations = getCombination(rest, selectNumber - 1);
        const attached = combinations.map((el => [fixed,...el]));

        result.push(...attached);

    });

    return result;
};

about 4 years ago · Juan Pablo Isaza
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