I have an array of some arbitrary int
values; I want to find the array containing the sum of the past elements in the current index.
Example:
int[] myArray = new int[5]{ 5, 7, 8, 2, 6 };
I would attempt to:
myArray[0] = 5
myArray[1] = myArray[0] + myArray[currentIndex] = 5 + 7
myArray[2] = 5 + 12 + 8
and so forth till my finished array is:[5, 12, 25, 44, 92]
I have 2 solutions, one in Java 7, and the other in Java 8, and I was wondering if it was possible to get critiqued on both of them, specifically on how to make the code more terse and efficient i.e. cutting out unnecessary steps or operations.
Java 7 (or language agnostic) solution:
public static int[] sumifyIn7(int[] array) {
int length = array.length;
for(int i = 1; i < length; i++) {
int sumSoFar = 0;
for(int j = 0; j <= i; j ++) {
sumSoFar += array[j];
}
array[i] = sumSoFar;
}
return array;
}
Side-note: Am I correct in saying this solution is \$O(nlog(n))\$?
Java 8 solution:
I'm very unfamiliar with Java 8, and plan on getting up to date with it during the school year, but this is what I could put together, but I'm sure it could be improved based on how redundant it seems.
public static int[] sumifyIn8(int[] array) {
int length = array.length;
for (int i = 1; i < length; i++) {
array[i] = Arrays.stream(Arrays.copyOfRange(array, 0, i + 1)).sum();
}
return array;
}
Test:
public static void main(String[] args) {
System.out.println(Arrays.toString(sumifyIn8(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 })));
System.out.println(Arrays.toString(sumifyIn7(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 })));
}
Test Results:
[1, 3, 7, 15, 31, 63, 127, 255, 511, 1023] [1, 3, 7, 15, 31, 63, 127, 255, 511, 1023]