Home > OS >  Recursive array function to append to
Recursive array function to append to

Time:10-09

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.

    public static float[] ratioArray(int pounds[],int price[],int arrayLength) {
        float[] priceRatio = new float[arrayLength];
        
    
        for (int 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.

CodePudding user response:

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));

  • Related