This project has retired. For details please refer to its Attic page.
Source code
001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *   http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing,
013 * software distributed under the License is distributed on an
014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 * KIND, either express or implied.  See the License for the
016 * specific language governing permissions and limitations
017 * under the License.
018 */
019package org.apache.reef.examples.group.utils.math;
020
021import java.util.ArrayList;
022import java.util.List;
023import java.util.logging.Level;
024import java.util.logging.Logger;
025
026/**
027 * Maintaining a fixed-size queue for sliding window operation.
028 */
029public class Window {
030
031  private final int maxSize;
032  private final List<Double> list;
033
034  public Window(final int size) {
035    this.maxSize = size;
036    list = new ArrayList<>(size);
037  }
038
039  public void add(final double d) {
040    if (list.size() < maxSize) {
041      list.add(d);
042      return;
043    }
044    list.remove(0);
045    list.add(d);
046  }
047
048  public double avg() {
049    if (list.size() == 0) {
050      return 0;
051    }
052    double retVal = 0;
053    for (final double d : list) {
054      retVal += d;
055    }
056    return retVal / list.size();
057  }
058
059  public double avgIfAdded(final double in) {
060    double d = in;
061    if (list.isEmpty()) {
062      return d;
063    }
064    final int start = list.size() < maxSize ? 0 : 1;
065    final int numElems = list.size() < maxSize ? list.size() + 1 : maxSize;
066    for (int i = start; i < list.size(); i++) {
067      d += list.get(i);
068    }
069    return d / numElems;
070  }
071
072  public static void main(final String[] args) {
073    final Logger log = Logger.getLogger(Window.class.getName());
074    final Window w = new Window(3);
075    for (int i = 1; i < 10; i++) {
076      final double exp = w.avgIfAdded(i);
077      w.add(i);
078      final double act = w.avg();
079      log.log(Level.INFO, "OUT: Exp: {0} Act: {1}", new Object[] {exp, act});
080    }
081  }
082}