JAVA的Collections类中shuffle的用法

来源:互联网 发布:一本好书 知乎 编辑:程序博客网 时间:2024/06/05 03:59

  1. import java.util.*;  
  2.   
  3. public class ShuffleTest {  
  4.     public static void main(String[] args) {  
  5.         List<Integer> list = new ArrayList<Integer>();  
  6.         for (int i = 0; i < 10; i++)  
  7.             list.add(new Integer(i));  
  8.         System.out.println("打乱前:");  
  9.         System.out.println(list);  
  10.   
  11.         for (int i = 0; i < 5; i++) {  
  12.             System.out.println("第" + i + "次打乱:");  
  13.             Collections.shuffle(list);  
  14.             System.out.println(list);  
  15.         }  
  16.     }  
  17. }  

输出结果:

打乱前:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
第0次打乱:
[6, 3, 2, 0, 8, 1, 7, 5, 4, 9]
第1次打乱:
[6, 2, 3, 0, 8, 5, 7, 4, 9, 1]
第2次打乱:
[1, 7, 9, 4, 6, 0, 2, 5, 3, 8]
第3次打乱:
[0, 4, 2, 8, 9, 1, 3, 7, 5, 6]
第4次打乱:
[8, 1, 3, 0, 7, 9, 4, 2, 5, 6]


在研究用遗传算法等启发式算法解决旅行商问题(Traveling Salesman Problem,TSP)时,首先要解决的问题时如何生成一个初始解,即一个代表顾客位置的编码序列,如有5个顾客,如何生成1,2,3,4,5的乱序序列,一般情况下是这样生成的:

方法一:

[java] view plain copy
  1. /* 
  2.      * @para len represents the length of the solution array 
  3.      *  
  4.      * function you input a length of an array,this method will return an array  
  5.      * of number from 1 to len with unsorted. 
  6.      */  
  7.     public int[] createSolution(int len) {  
  8.         int solutionArr[] = new int[len];  
  9.         Random random = new Random();  
  10.         int j = 0;  
  11.         solutionArr[0] = random.nextInt(len) + 1;  
  12.         for (int i = 1; i < len; i++) {  
  13.             j = 0;  
  14.             while (j != i) {  
  15.                 j = 0;  
  16.                 solutionArr[i] = random.nextInt(len) + 1;  
  17.                 while (j < i && solutionArr[j] != solutionArr[i])  
  18.                     j++;  
  19.             }  
  20.         }  
  21.         return solutionArr;  
  22.     }  
如上述代码所示,给定一个参数len,上述方法可以返回一个返回从1到len的一个len大小的乱序数组,很显然,上述方式生成一个乱序数组的方式是非常低效的。其实我们可以先生成一个顺序数组再想办法将其顺序打乱,代码如下:

方法二:

[java] view plain copy
  1. /* 
  2.      * @para len represents the length of the solution array 
  3.      *  
  4.      * function you input a length of an array,this method will return an array 
  5.      * of number from 1 to len with unsorted. 
  6.      */  
  7.     public int[] createSolution1(int len) {  
  8.         int solutionArr[] = new int[len];  
  9.         Random random = new Random();  
  10.         for (int i = 0; i < len; i++)  
  11.             solutionArr[i] = i + 1;  
  12.         int endIndex = len / 2, ranIndex1 = 0, ranIndex2 = 0;  
  13.         for (int i = 0; i <= endIndex; i++) {  
  14.             ranIndex1 = random.nextInt(len);  
  15.             ranIndex2 = random.nextInt(len);  
  16.             while (ranIndex1 == ranIndex2)  
  17.                 ranIndex2 = random.nextInt(len);  
  18.             swap(solutionArr, ranIndex1, ranIndex2);  
  19.         }  
  20.         return solutionArr;  
  21.     }  
         用上述方式比第一种方式减少了许多运算量,但是整个数组的乱序效果却不是很好,有没有一种效果很好的同时运算量又非常小的乱序方式呢。不用同时生成两个randomIndex,生成一个就行,然后从头到尾与randomIndex进行交换即可,代码如下:

方法二的改进版:

[java] view plain copy
  1. public int[] createSolution3(int len) {  
  2.         int solutionArr[] = new int[len];  
  3.         int ranIndex=0;  
  4.         Random random = new Random();  
  5.         for (int i = 0; i < len; i++)  
  6.             solutionArr[i] = i + 1;  
  7.         for (int i = 0; i <len; i++) {  
  8.             ranIndex = random.nextInt(len);  
  9.             swap(solutionArr, ranIndex, i);  
  10.         }  
  11.         return solutionArr;  
  12.     }  

方法二的改进版的实现方式为从头到尾将每个元素与随机生成的下标所对应的元素进行交换以达到相应的乱序效果。


方法三:

其实Java.util.Collections
里面提供了一个shuffle的接口,它可以很方便地将一个有序数组进行乱序处理。

[java] view plain copy
  1. /* 
  2.      * @para len represents the length of the solution array 
  3.      *  
  4.      * function you input a length of an array,this method will return an array 
  5.      * of number from 1 to len with unsorted. 
  6.      */  
  7.     public Integer[] createSolution2(int len) {  
  8.         Integer solutionArr[] = new Integer[len];  
  9.         List list=new ArrayList<Integer>();  
  10.         for (int i = 0; i < len; i++)  
  11.             list.add(i+1);  
  12.         Collections.shuffle(list);  
  13.         list.toArray(solutionArr);  
  14.         return solutionArr;  
  15.     }  

从eclipse查看shuffle接口的实现源码:

[java] view plain copy
  1. /** 
  2.      * Randomly permute the specified list using the specified source of 
  3.      * randomness.  All permutations occur with equal likelihood 
  4.      * assuming that the source of randomness is fair.<p> 
  5.      * 
  6.      * This implementation traverses the list backwards, from the last element 
  7.      * up to the second, repeatedly swapping a randomly selected element into 
  8.      * the "current position".  Elements are randomly selected from the 
  9.      * portion of the list that runs from the first element to the current 
  10.      * position, inclusive.<p> 
  11.      * 
  12.      * This method runs in linear time.  If the specified list does not 
  13.      * implement the {@link RandomAccess} interface and is large, this 
  14.      * implementation dumps the specified list into an array before shuffling 
  15.      * it, and dumps the shuffled array back into the list.  This avoids the 
  16.      * quadratic behavior that would result from shuffling a "sequential 
  17.      * access" list in place. 
  18.      * 
  19.      * @param  list the list to be shuffled. 
  20.      * @param  rnd the source of randomness to use to shuffle the list. 
  21.      * @throws UnsupportedOperationException if the specified list or its 
  22.      *         list-iterator does not support the <tt>set</tt> operation. 
  23.      */  
  24.     public static void shuffle(List<?> list, Random rnd) {  
  25.         int size = list.size();  
  26.         if (size < SHUFFLE_THRESHOLD || list instanceof RandomAccess) {  
  27.             for (int i=size; i>1; i--)  
  28.                 swap(list, i-1, rnd.nextInt(i));  
  29.         } else {  
  30.             Object arr[] = list.toArray();  
  31.   
  32.             // Shuffle array  
  33.             for (int i=size; i>1; i--)  
  34.                 swap(arr, i-1, rnd.nextInt(i));  
  35.   
  36.             // Dump array back into list  
  37.             ListIterator it = list.listIterator();  
  38.             for (int i=0; i<arr.length; i++) {  
  39.                 it.next();  
  40.                 it.set(arr[i]);  
  41.             }  
  42.         }  
  43.     }  
        从上述代码可以知道,shuffle的参数为一个List列表和一个Random对象,当List比较大时,选择首先将list通过list.toArray()转换成数组,然后按方法二的改进形式交换数组中元素的值,最后将list中的值依次替换为数组中的值,返回list对象。
        其实,方法二的改进方法和方法三种shuffle的在JAVA中的实现方式是类似的,很简单不是吗?而这种思路就来自 Ronald Fisher 和 Frank Yates首先提出的Fisher–Yates shuffle洗牌算法,但该算法的适合计算机运算的版本是由Richard Durstenfeld和Donald E. Knuth发扬光大的,Durstenfeld将该算法的时间复杂度由Fisher–Yates 提出算法的O(n*n)降低到O(n),其算法的伪码如下:

[java] view plain copy
  1. -- To shuffle an array a of n elements (indices 0..n-1):  
  2. for i from n−1 downto 1 do  
  3.      j ← random integer such that 0 ≤ j ≤ i  
  4.      exchange a[j] and a[i]  
该算法的另外一个版本为从最小的index开始至最高的index的过程:
[java] view plain copy
  1. -- To shuffle an array a of n elements (indices 0..n-1):  
  2. for i from 0 to n−2 do  
  3.      j ← random integer such that 0 ≤ j < n-i  
  4.      exchange a[i] and a[i+j]  

原创粉丝点击