Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

184
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!