本帖最后由 刘文超 于 2013-1-2 15:39 编辑
一般计算机的随机数都是“伪随机数”,以一个随机种子作为初始条件,然后用一定的算法不停迭代产生随机数。 随机种子可以是当前的系统时间,又叫真随机数 。
而shuffle只是应用了random而已,比较简单,很好理解:
这个是shuffle的主要思想:- To shuffle an array a of n elements (indices 0..n-1):
- for i from n − 1 downto 1 do
- j ← random integer with 0 ≤ j ≤ i
- exchange a[j] and a[i]
复制代码 就是说逆序遍历一个数组(集合),每一个元素 i 都与 “它之前那些元素(0~ i)中随机的一个元素” 进行互换。
这是JDK源代码:- /**
- * Moves every element of the List to a random new position in the list.
- *
- * @param list
- * the List to shuffle
- *
- * @throws UnsupportedOperationException
- * when replacing an element in the List is not supported
- */
- public static void shuffle(List<?> list) {
- shuffle(list, new Random());
- }
-
- /**
- * Moves every element of the List to a random new position in the list
- * using the specified random number generator.
- *
- * @param list
- * the List to shuffle
- * @param random
- * the random number generator
- *
- * @throws UnsupportedOperationException
- * when replacing an element in the List is not supported
- */
- @SuppressWarnings("unchecked")
- public static void shuffle(List<?> list, Random random) {
- if (!(list instanceof RandomAccess)) {
- Object[] array = list.toArray();
- for (int i = array.length - 1; i > 0; i--) {
- int index = random.nextInt(i + 1);
- if (index < 0) {
- index = -index;
- }
- Object temp = array[i];
- array[i] = array[index];
- array[index] = temp;
- }
-
- int i = 0;
- ListIterator<Object> it = (ListIterator<Object>) list
- .listIterator();
- while (it.hasNext()) {
- it.next();
- it.set(array[i++]);
- }
- } else {
- List<Object> rawList = (List<Object>) list;
- for (int i = rawList.size() - 1; i > 0; i--) {
- int index = random.nextInt(i + 1);
- if (index < 0) {
- index = -index;
- }
- rawList.set(index, rawList.set(i, rawList.get(index)));
- }
- }
- }
复制代码 |