1 /******************************************************************************* 2 * SAT4J: a SATisfiability library for Java Copyright (C) 2004, 2012 Artois University and CNRS 3 * 4 * All rights reserved. This program and the accompanying materials 5 * are made available under the terms of the Eclipse Public License v1.0 6 * which accompanies this distribution, and is available at 7 * http://www.eclipse.org/legal/epl-v10.html 8 * 9 * Alternatively, the contents of this file may be used under the terms of 10 * either the GNU Lesser General Public License Version 2.1 or later (the 11 * "LGPL"), in which case the provisions of the LGPL are applicable instead 12 * of those above. If you wish to allow use of your version of this file only 13 * under the terms of the LGPL, and not to allow others to use your version of 14 * this file under the terms of the EPL, indicate your decision by deleting 15 * the provisions above and replace them with the notice and other provisions 16 * required by the LGPL. If you do not delete the provisions above, a recipient 17 * may use your version of this file under the terms of the EPL or the LGPL. 18 * 19 * Based on the original MiniSat specification from: 20 * 21 * An extensible SAT solver. Niklas Een and Niklas Sorensson. Proceedings of the 22 * Sixth International Conference on Theory and Applications of Satisfiability 23 * Testing, LNCS 2919, pp 502-518, 2003. 24 * 25 * See www.minisat.se for the original solver in C++. 26 * 27 * Contributors: 28 * CRIL - initial API and implementation 29 *******************************************************************************/ 30 package org.sat4j.minisat.core; 31 32 import java.io.Serializable; 33 34 /** 35 * Create a circular buffer of a given capacity allowing to compute efficiently 36 * the mean of the values storied. 37 * 38 * @author leberre 39 * 40 */ 41 public class CircularBuffer implements Serializable { 42 43 /** 44 * 45 */ 46 private static final long serialVersionUID = 1L; 47 private final int[] values; 48 private int index = 0; 49 private long sum = 0; 50 private boolean full = false; 51 52 public CircularBuffer(int capacity) { 53 this.values = new int[capacity]; 54 } 55 56 public void push(int value) { 57 if (!this.full) { 58 this.values[this.index++] = value; 59 this.sum += value; 60 if (this.index == this.values.length) { 61 this.full = true; 62 this.index = -1; 63 } 64 return; 65 } 66 this.index++; 67 if (this.index == this.values.length) { 68 this.index = 0; 69 } 70 // buffer full, overwrite 71 this.sum -= this.values[this.index]; 72 this.values[this.index] = value; 73 this.sum += value; 74 } 75 76 public long average() { 77 if (this.full) { 78 return this.sum / this.values.length; 79 } 80 if (this.index == 0) { 81 return 0; 82 } 83 return this.sum / this.index; 84 } 85 86 public void clear() { 87 this.index = 0; 88 this.full = false; 89 this.sum = 0; 90 } 91 92 public boolean isFull() { 93 return this.full; 94 } 95 }