Skip to content

Instantly share code, notes, and snippets.

@ClickerMonkey
Created September 2, 2014 15:27
Show Gist options
  • Save ClickerMonkey/639c304906fa609903d2 to your computer and use it in GitHub Desktop.
Save ClickerMonkey/639c304906fa609903d2 to your computer and use it in GitHub Desktop.
Class used to iterate N items as if they were shuffled.
public class Shuffle
{
public int n;
public int[] index;
public long seed;
public Shuffle( int size )
{
this( System.currentTimeMillis(), size );
}
public Shuffle( long seed, int size )
{
this.seed = seed;
this.index = new int[size];
this.n = size;
for ( int i = 0; i < size; i++ )
{
this.index[i] = i;
}
}
public void reset()
{
n = index.length;
}
public int next()
{
seed ^= (seed << 21);
seed ^= (seed >>> 35);
seed ^= (seed << 4);
int relativeIndex = (int)(Math.abs( seed ) % n);
int actualIndex = index[relativeIndex];
index[relativeIndex] = index[--n];
index[n] = actualIndex;
return actualIndex;
}
}
public class ShuffleTest
{
public static void main(String[] args)
{
Shuffle shuffle = new Shuffle( 10 );
// prints out 0 through 9
for (int i = 0; i < 10; i++) {
System.out.print( shuffle.next() );
System.out.print( " " );
}
System.out.println();
shuffle.reset();
for (int i = 0; i < 10; i++) {
System.out.print( shuffle.next() );
System.out.print( " " );
}
System.out.println();
shuffle.reset();
for (int i = 0; i < 10; i++) {
System.out.print( shuffle.next() );
System.out.print( " " );
}
System.out.println();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment