Question

So here is the problem: create a int [] recursive method that computes cumulative sums in the array numbers, and transform each value in the array by adding to the value the sum of values that precede it in the array. For example, if

numbers = [5, 6, 7, 2, 3, 1], then

result = [5, (5)+6, (5+6)+7, (5+6+7)+2, (5+6+7+2)+3, (5+6+7+2+3)+1],

i.e.,result = [5, 11, 18, 20, 23, 24].

The caveats are: Cannot use static or void methods, cannot use loops. Here is my code so far:

    public int[] computeCumulativeSums(int[] numbers){

    if(numbers.length == 0)
    {
        return numbers; // Base case
    }
    else
    {
        //recursive stage not implemented. Don't know how to implement
        return numbers; 
    }

}
//Helper method
public int [] addNumbers(int [] list, int index)
{
    if(index == 0)
    {
        return list; //Helper method base case
    }
    else
    {
                    //recursive case
        return addNumbers(list, index - 1);
    }
}

public boolean searchTable(int[][] data, int element){
    return true;
}


public static void main(String [] args){

    Recursion r = new Recursion();
        int[] numbers = new int[] {5, 6, 7, 2, 3, 1};
    System.out.println(Arrays.toString(r.computeCumulativeSums(numbers)));  
}

Output: [5, 6, 7, 2, 3, 1]

What I'm asking is a push in the right direction because I'm so lost with this. Your help will be much appreaciated.

Was it helpful?

Solution 2

State your strategy .. then code the recursive function. You would probably have something like:

function summit(array, i) ... 
    if i > 0, then set array[i]=array[i-1]+array[i]
    if i < array.length the call summit(array,i+1)
    return

OTHER TIPS

What I would recommend is: try to do it with a while loop. The conditions. In the while loop is your stop condition. Now try to convert what is in the while loop into a recursive method (or if you can't, just a method, and then see how the each method could do the following call of the method itself). Does it help you?

public static void main(String args [])
{
   int [] array = {5,6,7,2,3,1};
   array = sum(array,0);
   for(int i=0; i<array.length; i++){
       System.out.print(" "+array[i]);
   }

}

public static int[] sum(int[] array, int index){
    if(index==array.length){
        return array;
    }
    if(index!=0){
        array[index] += array[index-1];
    }

    return sum(array,index+1);

}

Output: 5 11 18 20 23 24

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top