Reads a list of strings & prints them in random order.
This file contains 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 Knuth | |
{ | |
private Knuth() { } | |
public static void shuffle( Object[] a ) | |
{ | |
int n = a.length; | |
for ( int i = 0; i < n; i++ ) | |
{ | |
int r = (int) ( Math.random() * ( i + 1 ) ); | |
Object swap = a[r]; | |
a[r] = a[i]; | |
a[i] = swap; | |
} | |
} | |
public static void shuffleAlternate( Object[] a ) | |
{ | |
int n = a.length; | |
for ( int i = 0; i < n; i++ ) | |
{ | |
int r = i + (int) ( Math.random() * (n - i) ); | |
Object swap = a[r]; | |
a[r] = a[i]; | |
a[i] = swap; | |
} | |
} | |
public static void main( String[] args ) | |
{ | |
String[] a = StdIn.readAllStrings(); | |
Knuth.shuffle(a); | |
for ( int i = 0; i < a.length; i++ ) | |
StdOut.println( a[i] ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment