简体   繁体   中英

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

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

    // recurse
    int tailResult = addOddAndSubtractEvenPositions(values, position + 1);

    // calculate
    int currentValue = values.get(position);
    if (position % 2 == 0) {
         currentValue = -currentValue;
    }       
    return currentValue + tailResult;   
}

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

I haven't understood what the parameter k is used for But a recursive method to subtract the elements in pair and then sum all the pairs can be:

public static int SumSub(ArrayList<Integer> list){

    int result = 0;
    int size = list.size();

    if(list.size() > 2){

        for(int i = 0; i < size; i++){

            ArrayList<Integer> newList1 = new ArrayList<Integer>(list.subList(i, i+2));
            result += SumSub(newList1);
            i++;

        }

    } else {
        result = list.get(0) - list.get(1);
    }

    return result;  
}   

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM