国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

Java中打亂一個數組的2種公平算法分享

2019-11-26 15:14:38
字體:
來源:轉載
供稿:網友

公平算法,打亂數組

這是前幾天面試的時候遇見的一道題目,看到這個題首先想到了洗牌程序:

方法一:洗牌程序原理

在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類中的隨機數的生成的工具類,這個隨機類需要單獨研究一下。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 龙泉市| 安宁市| 澳门| 清水河县| 宁乡县| 胶南市| 临清市| 北碚区| 阿拉善左旗| 扎兰屯市| 内江市| 名山县| 沙河市| 林西县| 赣榆县| 五家渠市| 东阳市| 双辽市| 通河县| 沧州市| 彭水| 黑水县| 大连市| 盐源县| 格尔木市| 湖北省| 太仆寺旗| 宁化县| 长治市| 高要市| 张家川| 阜新市| 澜沧| 嘉善县| 兖州市| 吐鲁番市| 西平县| 甘谷县| 岱山县| 常熟市| 慈利县|