/*******************************************************************************
 * Copyright (c) 2013 Attila Kovacs <attila[AT]sigmyne.com>.
 * All rights reserved. 
 * 
 * This file is part of jnum.
 * 
 *     jnum is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 * 
 *     jnum is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU General Public License for more details.
 * 
 *     You should have received a copy of the GNU General Public License
 *     along with jnum.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * Contributors:
 *     Attila Kovacs <attila[AT]sigmyne.com> - initial API and implementation
 ******************************************************************************/
package jnum.util;

import java.util.Random;


// TODO: Auto-generated Javadoc
/**
 * A Random generator with a backing buffer.
 * 
 * BufferedRandom keeps a collection of Random numbers and bits, generated by the {@link java.util.Random}, from which it
 * randomly picks a value upon request. At the same time, a new random number is buffered in that same slot. The buffering
 * of random numbers is expected to reduce correlations between calls.
 */
public class BufferedRandom extends Random {
	
	/** The buffer. */
	private int[][] buffer;
	
	/**
	 * Instantiates a new buffered random.
	 */
	public BufferedRandom() {
		this(100);
	}
	
	/**
	 * Instantiates a new buffered random.
	 *
	 * @param size the size
	 */
	public BufferedRandom(int size) {
		buffer = new int[32][size];
		for(int bits=1; bits<32; bits++) for(int i=0; i<size; i++) buffer[bits][i] = super.next(bits);	
	}
	
	/**
	 * Use the current timestamp for seeding the random generator.
	 */
	public void seedNow() {
		setSeed(System.currentTimeMillis());
	}
	
	/* (non-Javadoc)
	 * @see java.util.Random#next(int)
	 */
	@Override
	public int next(int bits) {
		final int i = (int) (buffer.length * Math.random());
		final int value = buffer[bits][i];
		buffer[bits][i] = super.next(bits);
		return value;
	}
	
	/** The Constant serialVersionUID. */
	private static final long serialVersionUID = -8696559579537431957L;

}
