Shuffle.java


Below is the syntax highlighted version of Shuffle.java from §2.5 Arrays.


/*************************************************************************
 *  Compilation:  javac Shuffle.java
 *  Execution:    java Shuffle N < list.txt
 *  
 *  Reads in a list of N strings and prints them in random order.
 *
 *  The file california-gov.txt contains a list of the 135
 *  candidates in the October 7, 2003 California governor's runoff
 *  election. The file cards.txt contains a list of 52 playing cards.
 *  Both files use the _ character instead of whitespace to ensure
 *  that the full name can be read in with StdIn.readString().
 *
 *  % java Shuffle 5 < california-gov.txt
 *  Iris_Adam
 *  Douglas_Anderson
 *  Alex-St._James
 *  Angelyne
 *  Brooke_Adams
 *
 *  % java Shuffle 135 < california-gov.txt
 *  ...
 *
 *  % java Shuffle 5 < cards.txt
 *  Four_of_Clubs
 *  Six_of_Clubs
 *  Three_of_Clubs
 *  Deuce_of_Clubs
 *  Five_of_Clubs
 *
 *  % java Shuffle 52 < cards.txt
 *  ...
 *
 *************************************************************************/

public class Shuffle { 
    public static void main(String[] args) { 
        int N = Integer.parseInt(args[0]);
        String[] a = new String[N];

        // read in data
        for (int i = 0; i < N; i++) {
            a[i] = StdIn.readString();
        }

        // shuffle
        for (int i = 0; i < N; i++) {
            int r = (int) (Math.random() * (i+1));     // int between 0 and i
            String swap = a[r];
            a[r] = a[i];
            a[i] = swap;
        }

        // print permutation
        for (int i = 0; i < N; i++)
            System.out.println(a[i]);

    }
}


Last updated: Wed Sep 22 10:23:44 EDT 2004 .
Copyright © 2004, Robert Sedgewick and Kevin Wayne.