本文主要是介绍Moving Average of An Input Stream,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Moving Average of An Input Stream. The size of a window is n
For example:
input = [1, 1, 2, 3, 3, 4, 4, 4, 5.....], n = 3;
moving average = [1, 1, 1.33, 2, 2.67, 3.33, 3.67, 4, 4.33...]
public void movingAverage(Stream input, int windowSize)
最下面的做法不是动态的,改为如下,同时也得改之前的另一道题。
public class MovingAverage {Queue<Integer> list;int size = 0;int sum = 0;/** Initialize your data structure here. */public MovingAverage(int size) {list = new LinkedList<>();this.size = size;}public double next(int val) {double result = 0.0;if (list.size() < size) {sum = sum + val;list.offer(val);result = (double)sum / list.size();} else {int deletedNum = list.poll();sum = sum - deletedNum;sum = sum + val;result = (double)sum / size;list.offer(val);}return result;}
}/*** Your MovingAverage object will be instantiated and called as such:* MovingAverage obj = new MovingAverage(size);* double param_1 = obj.next(val);*/
import java.text.DecimalFormat;public class MovingAverage {private static DecimalFormat df2 = new DecimalFormat(".##");public static void main(String[] args) {// TODO Auto-generated method stubint[] array = {1, 1, 2, 3, 3, 4, 4, 4, 5};double[] arrays = movingAverage(array, 3);for (double d: arrays) {
// System.out.format("%.2f",d);
// System.out.println("");System.out.println(df2.format(d));}}private static double[] movingAverage(int[] array, int n) {double[] res = new double[array.length];int sum = 0;for (int i = 0; i < array.length; i++) {if (i < n) {sum = sum + array[i];res[i] = (double)sum/(i + 1);} else {sum = sum - array[i - n];sum = sum + array[i];res[i] = (double)sum/n;}}return res;}
}
这篇关于Moving Average of An Input Stream的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!