Shuffler Enum
//package gameEngine.logic.utils;
import java.lang.reflect.Array;
import java.util.Random;
public class Shuffler<T extends Enum<?>>
{
private T m_Array[] = null;
private int m_Index = 0;
@SuppressWarnings("unchecked")
public Shuffler(int size, int quantitiesArr[], Class<T> type)
{
m_Array = (T[])Array.newInstance(type, size);
int startIndex = 0;
for (T currValue : type.getEnumConstants())
{
int currIndex = currValue.ordinal();
if (currIndex >= quantitiesArr.length)
{
break;
}
if (quantitiesArr[currIndex] == 0)
{
continue;
}
initElements(startIndex, quantitiesArr[currIndex], currValue);
startIndex += quantitiesArr[currIndex];
}
Randomizer.generatePermutationOnArray(m_Array);
}
private void initElements(
int startingIndex,
int numberOfElements,
T elemValue
)
{
for (int i = 0; i < numberOfElements; i++)
{
m_Array[i + startingIndex] = elemValue;
}
}
public void shuffle()
{
if (m_Array != null)
{
Randomizer.generatePermutationOnArray(m_Array);
}
reset();
}
public void reset()
{
m_Index = 0;
}
public T getNext()
{
try
{
return m_Array[m_Index++];
}
catch(ArrayIndexOutOfBoundsException e)
{
return null;
}
}
public T peek()
{
if (m_Index >= m_Array.length)
{
return null;
}
else
{
return m_Array[m_Index];
}
}
}
class Randomizer
{
static
{
m_Random = new Random();
}
public static void generatePermutationOnArray(Object[] array)
{
Object tmp = null;
int currIndex = 0;
for (int i = array.length; i > 0; i--)
{
currIndex = m_Random.nextInt(i);
tmp = array[currIndex];
array[currIndex] = array[i - 1];
array[i - 1] = tmp;
}
}
public static int getRandomNumber(int lowerBound, int higherBound)
{
int delta = higherBound - lowerBound + 1;
return (m_Random.nextInt(delta) + lowerBound);
}
private static Random m_Random;
public static void main(String args[])
{
Integer arr[] = new Integer[20];
for (int i = 0; i < 20; i++)
{
arr[i] = new Integer(i);
}
for (int i = 0; i < 5; i++)
{
System.out.println("");
generatePermutationOnArray(arr);
}
}
public static double getRandomDouble()
{
double rand = m_Random.nextDouble();
boolean flag = m_Random.nextBoolean();
if (flag == true)
{
rand *= -1.0;
}
return rand;
}
}
Related examples in the same category