Skip to content

Instantly share code, notes, and snippets.

@paullewallencom
Created July 24, 2018 23:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paullewallencom/c672a9368fe93a19d076c58458f54f4f to your computer and use it in GitHub Desktop.
Save paullewallencom/c672a9368fe93a19d076c58458f54f4f to your computer and use it in GitHub Desktop.
Reads a list of strings & prints them in random order.
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