/src/com/yannickstucki/android/musicqueue/old/RandomSequence.java
Java | 74 lines | 29 code | 5 blank | 40 comment | 3 complexity | abace51a3c9378ff7019e62f5d2bb192 MD5 | raw file
1/* 2 * Copyright 2009 Yannick Stucki (yannickstucki.com) 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16package com.yannickstucki.android.musicqueue.old; 17 18import java.util.Random; 19 20/** 21 * A utility class for generating random sequences. 22 * 23 * @author Yannick Stucki (yannickstucki@gmail.com) 24 * 25 */ 26public final class RandomSequence { 27 28 /** 29 * Utility class cannot be instantiated. 30 */ 31 private RandomSequence() { 32 } 33 34 /** 35 * An array of prime numbers. We need a generator for every possible finite 36 * group. Any prime number is coprime and thus a generator, except when the 37 * group's cardinality is divided by the prime number. For that case we have 38 * an array of prime numbers, so one of them surely won't divide the group's 39 * cardinality. The only problem would occur if someone had the same amount of 40 * songs as a multiple of the product of all those prime numbers which is of 41 * course too big to be even an integer. 42 */ 43 private static final int[] X = new int[] { 19, 23, 29, 31, 37, 41, 43, 47, 44 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 45 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 46 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 47 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 48 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 49 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541 }; 50 51 /** 52 * Creates a (semi) random sequence of length n containing all the integers 53 * from 0 to n - 1. Not every sequence is possible, but since there's many 54 * prime numbers as potential generators, the variety will be big enough to 55 * appear random. This way we can generate a random sequence in O(n) instead 56 * of O(n^2). 57 */ 58 public static int[] get(int n) { 59 Random r = new Random(); 60 r.setSeed(System.currentTimeMillis()); 61 int index = r.nextInt(X.length); 62 int x = X[index]; 63 while (n % x == 0) { 64 index = (index + 1) % X.length; 65 x = X[index]; 66 } 67 int y = r.nextInt(X.length); 68 int[] randomSequence = new int[n]; 69 for (int i = 0; i < n; i++) { 70 randomSequence[i] = (x * i + y) % n; 71 } 72 return randomSequence; 73 } 74}