Created
September 2, 2014 15:27
-
-
Save ClickerMonkey/639c304906fa609903d2 to your computer and use it in GitHub Desktop.
Class used to iterate N items as if they were shuffled.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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