Java list value replacing -


if have java list 5 elements 0, 1, 2, 3, 4 had int number values. how can sum of combination of elements in place of elements combined

the packages using follows:

java.util.arraylist   java.util.linkedlist   java.util.vector   java.util.stack   java.util.iterator 

example

mylist(o) = 1   mylist(1) = 2   mylist(2) = 3   mylist(3) = 4   mylist(4) = 5   

i combine elements 1-3

mylist(0) = 1 mylist(1) = 9  //sum of elements 2,3,4, indexed 1-3 mylist(2) = 5 

what asking instead of automatically adding new value (in case 9) end of list place.

simply rebuild list , add elements within range:

public static list<integer> combine(list<integer> list, int start, int end) {     arraylist<integer> lst2 = new arraylist<>();     int sum = 0;     (int = 0; < list.size(); i++) {         //if not in combine range, add element new list         if (i < start || > end) {             lst2.add(list.get(i));         } else {             //otherwise, add element combine sum, , add list when done             sum += list.get(i);             if (i == end) {                 lst2.add(sum);             }         }     }     return lst2; } 

from example seems want range inclusive on both ends. if not (and end index should exclusive), change i > end i >= end , i == end i == end - 1.


Comments

Popular posts from this blog

Fail to load namespace Spring Security http://www.springframework.org/security/tags -

sql - MySQL query optimization using coalesce -

unity3d - Unity local avoidance in user created world -