In: Computer Science
Given an array ? of numbers and a window size ?, the sliding window ending at index ? is the subarray ?[? − ? + 1], ⋯ , ?[?] if ? ≥ ? − 1, and ?[0], ⋯ , ?[?] otherwise. For example, if ? = [0, 2, 4, 6, 8] and ? = 3, then the sliding windows ending at indices 0, 1, 2, 3 and 4 are respectively [0], [0, 2], [0, 2, 4], [2, 4, 6], and [4, 6, 8]. Write a method, movingAverage, that given as input an array ? of numbers and a window size ?, returns an array ? with the same length as ?, such that for every index ?, ?[?] is the average of the numbers in the sliding window ending at index ?. The skeleton for the method is provided in the file MovingAverage.java.
The following is a sample run.
Input: ? = [0,2, 4, 6, 8], ? = 3
Return: [0, 1, 2, 4, 6]
Explanation: As explained above, the sliding windows at indices 0, 1, 2, 3 and 4 are respectively
[0], [0,2], [0, 2, 4], [2, 4, 6], and [4, 6, 8]. The average of the numbers in these sliding windows are respectively = 0, = 1, = 2, = 4, and = 6.
Your method must have time complexity ?(?), where ? is the length of the input array ?.
Hint: You may find a queue useful.
public class MovingAverage {
public double[] movingAverage(int[] A, int w) {
//Replace this line with your
return statement
return null;
}
}
public static double[] movingAverage(int[] A, int w) { double result[] = new double[A.length]; double currentSum = 0; for(int i=0; i<A.length; i++) { currentSum += A[i]; if(i >= w) { currentSum -= A[i-w]; } int len = Math.min(i + 1, w); result[i] = currentSum/len; } // Replace this line with your return statement return result; }
************************************************** Thanks for your question. We try our best to help you with detailed answers, But in any case, if you need any modification or have a query/issue with respect to above answer, Please ask that in the comment section. We will surely try to address your query ASAP and resolve the issue.
Please consider providing a thumbs up to this question if it helps you. by Doing that, You will help other students, who are facing similar issue.