001package algs22;
002import stdlib.*;
003import java.security.SecureRandom;
004/* ***********************************************************************
005 *  Compilation:  javac SecureShuffle.java
006 *  Execution:    java SecureShuffle < list.txt
007 *
008 *  Reads in a list of strings and prints them in random order.
009 *  Our shuffling algorithm guarantees to rearrange the elements
010 *  in uniformly random order, under the assumption that Math.random()
011 *  generates independent and uniformly distributed numbers between
012 *  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 XSecureShuffle {
032        public static void main(String[] args) {
033
034                // read in the data
035                String[] a = StdIn.readAll().split("\\s+");
036                int N = a.length;
037
038                // create random array of real numbers between 0 and 1
039                SecureRandom random = new SecureRandom();
040                Double[] r = new Double[N];
041                for (int i = 0; i < N; i++) {
042                        r[i] = random.nextDouble();
043                }
044
045                // shuffle and get resulting permutation
046                int[] index = Merge.indexSort(r);
047
048                // print permutation
049                for (int i = 0; i < N; i++)
050                        StdOut.println(a[index[i]]);
051        }
052}