001package algs11;
002import stdlib.*;
003/* ***********************************************************************
004 *  Compilation:  javac Shuffle.java
005 *  Execution:    java Shuffle < list.txt
006 *  Data files:   http://algs4.cs.princeton.edu/11model/cards.txt
007 *
008 *  Reads in a list of strings and prints them in random order.
009 *  The Knuth (or Fisher-Yates) shuffling algorithm guarantees
010 *  to rearrange the elements in uniformly random order, under
011 *  the assumption that Math.random() generates independent and
012 *  uniformly distributed numbers between 0 and 1.
013 *
014 *  % more cards.txt
015 *  2C 3C 4C 5C 6C 7C 8C 9C 10C JC QC KC AC
016 *  2D 3D 4D 5D 6D 7D 8D 9D 10D JD QD KD AD
017 *  2H 3H 4H 5H 6H 7H 8H 9H 10H JH QH KH AH
018 *  2S 3S 4S 5S 6S 7S 8S 9S 10S JS QS KS AS
019 *
020 *  % java Shuffle < cards.txt
021 *  6H
022 *  9C
023 *  8H
024 *  7C
025 *  JS
026 *  ...
027 *  KH
028 *
029 *************************************************************************/
030
031public class Shuffle {
032        public static void main(String[] args) {
033                StdIn.fromFile ("data/cards.txt");
034
035                // read in the data
036                String[] a = StdIn.readAll().split("\\s+");
037                int N = a.length;
038
039                // shuffle
040                for (int i = 0; i < N; i++) {
041                        // int from remainder of deck
042                        int r = i + (int) (Math.random() * (N - i));
043                        String swap = a[r];
044                        a[r] = a[i];
045                        a[i] = swap;
046                }
047
048                // print permutation
049                for (int i = 0; i < N; i++)
050                        StdOut.println(a[i]);
051        }
052}