lundi 3 mars 2014

Java - Recursive Method that takes Cumulative sum in one array and returns another


Vote count:

0




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.



asked 22 secs ago






Aucun commentaire:

Enregistrer un commentaire