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

186
Visualizações
Adding elements into array with recursion

I have an array function that calculates the ratio of price to weight per pound. I wish to make this function recursive, or learn how to.

    function ratioArray(pounds,price,arrayLength) {
        float[] priceRatio = new float[arrayLength];
        
    
        for (var i = 0; i < arrayLength; i++) {
            priceRatio[i] = (float) price[i] / (float) pounds[i];
        }
        
        
        
        return priceRatio;
        
    }

What I have tried: using other function calls to try and make it recursive and return the values individually through recursion and then add them to an array (instead of returning the array, I would return the price to pound ratio and store that). However, I cannot get it to work recursively.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The general idea would be to see if the length is 0, if so, return an empty array. Otherwise, return an array with the ratio of the first element, plus whatever a call to ratioArray with the rest of the array (that is, with the first element of the arrays removed) returns.

In JS (so I can do a runnable example), it would look like:

function ratioArray(pounds, price, length) {
        if (length === 0) return [];
        const ratio = [price[0] / pounds[0]];
        const rest = ratioArray(pounds.slice(1), price.slice(1), length - 1)
        return ratio.concat(rest)
}

console.log(ratioArray([1, 2, 3, 4, 5], [100, 190, 270, 340, 400], 5));

Or if you want to avoid copying the array so much:

function ratioArray(pounds, price, length) {
        if (length === 0) return [];
        const ratio = price[0] / pounds[0];
        const rest = ratioArray(pounds.slice(1), price.slice(1), length - 1);
        rest.unshift(ratio);
        return rest;
}

console.log(ratioArray([1, 2, 3, 4, 5], [100, 190, 270, 340, 400], 5));

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