Java中打亂一個數組的2種公正算法分享。本站提示廣大學習愛好者:(Java中打亂一個數組的2種公正算法分享)文章只能為提供參考,不一定能成為您想要的結果。以下是Java中打亂一個數組的2種公正算法分享正文
公正算法,打亂數組
這是頭幾天面試的時刻碰見的一道標題,看到這個題起首想到了洗牌法式:
辦法一:洗牌法式道理
在java.util包中的Collections類中的 shuffle辦法,如今手工完成以下代碼以下:
package test.ms;
import java.util.Random;
public class Redistribute2 {
public static void main(String[] args) {
//define the array
int[] s = {1,5,4,3,6,9,8,7,0,8,5,6,7,2};
// before redistribute output
System.out.println("before redistribute:");
for(int i = 0 ; i<s.length; i++){
System.out.print(s[i]+" ");
}
// invoke the method
shuffle(s,new Random());
System.out.println();
// after redistribute output
System.out.println("after redistribute:");
for(int i = 0 ; i<s.length; i++){
System.out.print(s[i]+" ");
}
}
// using the random get the random number
public static void shuffle(int[] array, Random random){
for(int i = array.length; i >= 1; i--){
swap(array,i-1,random.nextInt(i));
}
}
// the two number swap in the array
public static void swap(int[] array, int i , int j){
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
swap辦法用於交流數組中的兩個數, shuffle辦法 用於 依據隨機源 生成的隨機數停止交流。
輸入成果以下:
before redistribute: 1 5 4 3 6 9 8 7 0 8 5 6 7 2 after redistribute: 9 8 7 8 0 6 1 6 5 5 2 3 7 4
辦法二:生成隨機索引交流
該辦法應用Set聚集的特征:Set聚集中的數據不反復,生成數組的索引,依據生成的索引停止交流數據。
完成方法以下:
package test.ms;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Random;
import java.util.Set;
public class Redistribute {
public static void main(String[] args) {
int[] s = {1,5,4,3,6,9,8,7,0,8,5,6,7,2};
redistribute(s);
}
public static void redistribute(int[] s){
Random random = new Random();
Set<Integer> set = new LinkedHashSet<Integer>();
// redistribute the index
while(true){
int t =random.nextInt(s.length);
set.add(t);
if(set.size()== s.length)
break;
}
System.out.println("before redistribute:");
for(int i = 0 ; i<s.length; i++){
System.out.print(s[i]+" ");
}
System.out.println();
System.out.println("redistribute the index ");System.out.println(set);
int [] out = new int[s.length];
int count = 0;
for(Iterator<Integer> iterator = set.iterator(); iterator.hasNext();){
out[count] = s[iterator.next()];
count++;
}
// out the result;
System.out.println("after redistribute:");
for(int i = 0 ; i<s.length; i++){
System.out.print(out[i]+" ");
}
}
}
這個辦法起首生成索引,然後依據新索引停止數據交流,代碼都寫在main辦法裡了,不是太好。
生成成果以下:
before redistribute: 1 5 4 3 6 9 8 7 0 8 5 6 7 2 redistribute the index [6, 2, 9, 1, 10, 5, 11, 4, 12, 3, 7, 8, 0, 13] after redistribute: 8 4 8 5 5 9 6 6 7 3 7 0 1 2
關於隨機數的生成,用了java類中的隨機數的生成的對象類,這個隨機類須要零丁研討一下。