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

130
Visualizações
I am making a recursive algorithm to return the length of the lowest row of a pyramid you are able to build with the input amount of blocks

It needs to still return the correct row in the case of a input number that doesn't make a full pyramid.
Inputs old, Internal, lr are all internal and shouldn't be required to fill in.

const pir = (Input, old, Internal, lr) => {
    console.log({
        Input, Internal, lr
    });
    if (Internal === undefined || lr === undefined || old === undefined) {
        Internal = 1;
        lr = 1;
        old = 1;
    }
    console.log({
        Input, Internal, lr
    });
    if ( ( Input === Internal ) || ( Input < Internal && old > Internal ) ) {
        return lr;
    } else {
        return pir(Input, Internal, Internal + (lr + 1), lr + 1)
    }
};
about 4 years ago · Santiago Gelvez
1 Respostas
Responde à pergunta

0

The condition old > internal is never going to be true.

You need to get the condition where there is an overrun only (not equality). When there is an overrun, return lr - 1, which is the previous value of lr, and which was OK:

if (Input < Internal) {
    return lr - 1; // Return previous value of lr (the last successful one)
}

Some other remarks:

  • You can give parameters default values in the function heading
  • Name your variables in camelCase (so not starting with a capital). It is common practice to reserve names with a starting capital (PascalCase) for constructors/classes.
  • And as you see from the above simplification, you don't really need the old argument

So here is how the function could look:

const pir = (input, internal=1, lr=1) => {
    if (input < internal) {
        return lr - 1; // Return previous value of lr (the last successful one)
    } else {
        return pir(input, internal + lr + 1, lr + 1)
    }
};

Finally, the relationship between the size and the width of such a "pyramid" is a mathematical one. This relationship can be solved in terms of the width, and so we can write pir as:

const pir = input => Math.floor((Math.sqrt(1+8*input) -1)/2);
about 4 years ago · Santiago Gelvez 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