Hispanish Hispanish - 6 months ago 8
Java Question

how can I get the result of addition and subtraction, with a recursive method that uses an ArrayList?

given a arraylist input, I have to create a recursive method that returns the sum of the values in the odd positions of the list from which the position of values are subtracted

For example:

private int method(ArrayList<Integer> list, int k)
{
int s = 0;
s = list.get(k);
if(k == list.size()) return s;
return s + method(k+1);
}

public int method(ArrayList<Integer> list)
{
return method(list,0);
}


(in main)

List<Integer> list = Arrays.asList(2, 5, 3, 7, 11, 1);
ArrayList<Integer> l2 = new ArrayList<>(list);
SumSub test = new SumSub(l2);
System.out.println(test.method(l2));


[2, 5, 3, 7, 11, 1] ---> 2-5+3-7+11-1=3 (the result that it should be showed)
but the result is always 22 and i can't understand why

Answer

Some pointers:

  • Give variables meaningful names, not k, s, list etc.
  • Declare collection interfaces (List) instead of implementation classes (ArrayList) where possible to improve the level of abstraction in your code.

Here an example of a recursive solution (untested):

private static int addOddAndSubtractEvenPositions(List<Integer> values, int position) {

    // stop condition
    if (position >= values.size()) {
        return 0;
    }

    // recursion
    int result = addOddAndSubtractEvenPositions(values, position + 1);
    int value = values.get(position);
    if (position % 2 == 0) {
         result -= value;
    }
    else {
        result += value;
    }    
    return result ;   
}

public static void main(String[] args) {
    List<Integer> values = Arrays.asList(2, 5, 3, 7, 11, 1);    
    System.out.println(addOddAndSubtractEvenPositions(values, 0));
}