/** We scramble the components of the vector. */ void scramble() { // (See "Applied Cryptography" by Bruce Schneier) int shuffle = size() - 1; for (int ii = shuffle; ii > 0; ii--) { int iiPermut = Math.abs(RandomSingleton.getInstance().nextInt()) % (ii + 1); if (iiPermut != ii) { Object permutObject = elementAt(ii); setElementAt(elementAt(iiPermut), ii); setElementAt(permutObject, iiPermut); } } }
/** * Constructs a random ranking of the numbers 1 through n. Throws an IllegalArgumentException if n * < 1. Must run in O(n log n) time <br> * <br> * <strong>Note:</strong> For random number generation, use the RandomSingleton class from Project * 1; this generator might be modified slightly for use in this project. To generate a random * permutation of 1 through n, use the <a href= * "http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm" >"shuffle" * algorithm</a> * * @param n Number of random rankings to create * @throws IllegalArgumentException if n < 1 */ public Ranking(int n) throws IllegalArgumentException { // Grab our Random object (You must use this class for anything Random!) Random rand = RandomSingleton.getInstance(); if (n < 1) { // If n is less than one, constructor will throw an // exception. throw new IllegalArgumentException("n has to be bigger than or equal to 1"); } else { // Otherwise it will make a shuffled permutation of n. Ranks = new int[n]; for (int i = 0; i < n; i++) { // O(n) Ranks[i] = i + 1; } for (int i = n - 1; i >= 0; i--) { // O(n) int index = 1 + rand.nextInt(i + 1); int temp = Ranks[index - 1]; Ranks[index - 1] = Ranks[i]; Ranks[i] = temp; } // Total time complexity: O(2n) = O(n) } }