2013-12-14 155 views
-3

嘿傢伙我試圖洗牌和整數數組。可以說我有這個數組:int [] array = {1,2,3,4,5}; 我想將其整理以便順序變得完全隨機。例如:int [] array = {3,5,1,4,2};對於java如何洗牌整數數組?

+0

編程語言shuffeld?你的「嘗試」代碼是? – Hardy

回答

2

不知道你在用什麼編程語言,但我會用Python來回答它。

from random import shuffle 
alist = [[i] for i in range(5)] 
shuffle(alist) 
1

洗牌的算法很簡單 - 但你需要得到它恰到好處或洗牌並不是隨機的。

在java中:

for (int i=0;i<arr.length;i++) { 
    int swap = random.nextInt(arr.length-i) + i; 
    int temp = arr[swap]; 
    arr[swap] = arr[i]; 
    arr[i]=temp; 
} 

基本上你在列表中有一個交換當前元素列表中的掃描隨手拈從自身到列表的末尾。

重要的是你只能選擇前進,否則你不會以均勻的分配結束。

大多數語言(包括Java)都有一個內置的shuffle函數。

0

我會回答在Java中:

int[] a = int[] { 1, 2, 3, 4, 5 }; // example array 

int length = a.length(); // for convenience, store the length of the array 

Random random1 = new Random(); // use a standard Java random number generator 

int swap = 0; // use an extra variable for storing the swap element 
int r1 = 0; // for convenience, store the current randomly generated number 

for (int i=0; i<length(); i++) { // iterate over each field of the array 

    r1 = random1.nextInt(length - 1); // generate a random number representing an index within the range of 0 - a.length - 1, i.e. the first and the last index of the array 

    swap = a[i]; // swap part 1 
    a[i] = a[r1]; // swap part 2 
    a[r1] = swap; // swap part 3 
} 

//就是這樣,陣列根據Java隨機生成