Skip to content

Instantly share code, notes, and snippets.

@mkdika
Created June 29, 2018 00:38
Show Gist options
  • Save mkdika/a8e836a55f4da7338e13e761d2445ea7 to your computer and use it in GitHub Desktop.
Save mkdika/a8e836a55f4da7338e13e761d2445ea7 to your computer and use it in GitHub Desktop.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
*
* @author Maikel Chandika ([email protected])
*
* Java Array Window Sliding Average.
* With O(n) time complexity.
*
*/
public class SlidingWindowAverage {
public static void main(String[] args) {
int[] input = {2, 3, 4, 5}; // -> [2.5, 3.5, 4.5]
System.out.println("before: " + Arrays.toString(input));
System.out.println("after : "+ Arrays.toString(calc(input, 2)));
System.out.println();
int[] input2 = {2, 3, 4, 5, 8, 9, 7}; // -> [2.5, 3.5, 4.5, 6.5, 8.5, 8]
System.out.println("before: " + Arrays.toString(input2));
System.out.println("after : "+ Arrays.toString(calc(input2, 2)));
System.out.println();
int[] input3 = {2, 5, 7}; // -> [3.5, 6]
System.out.println("before: " + Arrays.toString(input3));
System.out.println("after : "+ Arrays.toString(calc(input3, 2)));
}
static Double[] calc(int[] arr, int window) {
List<Double> r = new ArrayList<>();
int n = 1;
double sum = 0.0d, w = window, start = (double) arr[0];
for (int i = 0; i < arr.length; i++) {
double d = arr[i];
if (n < window) {
sum += d;
n++;
} else {
sum = sum + d;
r.add(sum / w);
sum = sum - start;
start = arr[i - (window - 2) > 0 ? i - (window - 2) : 0];
n = window < 3 ? window : window - 1;
}
}
return r.toArray(new Double[r.size()]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment