Java: how to sum element of an array one by one in the same array -
i´ve searched , thought lot can´t come solution.
given array of numbers, should sum each element next , write in same array, again , again until first position [0] of array contains sum of elements.
example: test[] = {1, 2, 3, 4, 5}
next step be:
test[0] = test[0] + test[1] = 1 + 2 = 3;
test[1] = test[2] + test[3] = 3 + 4 = 7;
test[2] = test[4] = 5;
array becomes: {3, 7, 5, 4, 5}
then repeats again:
test[0] = test[0] + test[1] = 3 + 7 = 10;
test[1] = test[3] = 5;
array becomes: {10, 5, 5, 4, 5}
then finaly again:
test[0] = test[0] + test[1] = 10 + 5 = 15;
array becomes: {15, 5 , 5, 4, 5}
i know list right solution exercise solve simple array. suggestions more welcome!
again: task not efficency solving using arrays. sorry first post , looks mess.
edit:
i´ve have come this:
for (int = 0; < test.length - (test.length / 2); i++) { test[i] = test[2 * i] + test[2 * + 1]; }
works incase of amount of given numbers , needs in loop repeated correct ammount of times.
this messy, works. modifies array in place, each time overwriting half(summed up) of array, odd amounts being kept in-place.
int[] test = { 1, 2, 3, 4, 5, 6 }; int l = test.length; { l = sumto(test, l); } while (l > 1); system.out.println(arrays.tostring(test));
sumto takes 2 arguments, array modified, , index sum to.
int sumto(int[] ar, int to) { int i; (i = 0; < to; += 2) { if (i == - 1) ar[i / 2] = ar[i]; else ar[i / 2] = ar[i] + ar[i + 1]; } return (i + 1) / 2; }
Comments
Post a Comment