問題的解決:
1、假設想要將2~7這6個數字隨機排序成一個數組,這里我們設置min為該范圍的最小值2,max為該范圍的上限7,n為想要在這個范圍中取出多少個數字組成一個數組,當然當n等於范圍的長度len即6時,那么得到的就是將原來的6個數字重新隨機排序一遍。
2、為了方便我們引進一個初始化數組source,並將剛剛范圍中的所有數字依次存進該數組中,則初始化數組source為{2,3,4,5,6,7}。
3、為了方便我們同樣再引進另一個數組result作為最后返回的數組。在這里我們知道一開始len=6,那么就隨機取得一個隨機數index(0<=index<=len-1),接下來就要在source數組中找到index位置上的元素放入到result數組的第0位,這時應該將len自減,同時在source數組中將source[index]替換為source[len]。
4、以此類推直到數組result已滿位置。最終得到的就是一個經過隨機排序的數組。
java代碼如下:
1 public class TestRandom { 2 /** 3 * 該方法用於在制定范圍即(min~max)內對min到max的所有數字進行重新隨機排列,使他們形成一組隨機數。 4 * 1、首先先初始化一個長度為(max-min+1)的數組source,數組的元素按照數字從大到小的順序分別為min~max; 5 * 2、每次取一個隨機數index,0<=index<=(數組長度len-1),同時len自減1, 6 * 取出source數組中對應在index位置上的元素依次放進最終數組result,並且將source[index]替換為source[len]。 7 **/ 8 9 public static int[] randomArray(int min,int max,int n){ 10 int len = max-min+1;//len為該范圍內元素的個數 11 12 if(max < min || n > len){ 13 return null; 14 } 15 16 //初始化給定范圍的待選數組 17 int[] source = new int[len]; 18 for (int i = min; i < min+len; i++){ 19 source[i-min] = i; 20 } 21 22 int[] result = new int[n]; 23 Random rd = new Random(); 24 int index = 0; 25 for (int i = 0; i < result.length; i++) { 26 //待選數組0到(len-2)隨機一個下標 27 index = Math.abs(rd.nextInt() % len--); 28 //將隨機到的數放入結果集 29 result[i] = source[index]; 30 //將待選數組中被隨機到的數,用待選數組(len-1)下標對應的數替換 31 source[index] = source[len]; 32 } 33 return result; 34 } 35 public static void main(String[] args) { 36 for (int i = 0; i<=5; i++) { 37 int result[]=TestRandom.randomArray(2,7,6); 38 for (int num:result) { 39 System.out.print(num+"\t"); 40 } 41 System.out.println(); 42 } 43 } 44 }
運行結果如圖,可見每次運行的結果都有可能不一樣。
2016-04-03
BOB