2012-03-29 47 views
0

我的問題是我想讓我的程序在0到3之間的數字範圍內做出四個唯一的隨機選擇我試圖在隨機班級中做到這一點,但我不能,如果你可以幫助代碼將是巨大的,我的計劃將是這樣的,以明確選擇具有特定範圍的唯一隨機數

my range 

0 1 2 3 randomly chosen number 3 

0 1 2 randomly chosen number 1 

0 2  randomly chosen number 2 

0  it will choose 0 and then the program closes 
+1

請顯示你寫的代碼。 – 2012-03-29 10:44:57

+1

您是從4組數字中選擇4個隨機數字(沒有替換)?你真的想達到什麼目的?你只是試圖隨機化數字0-3的序列? – 2012-03-29 10:51:10

+0

它實際上是一個功能不是整個程序,不試圖隨機我想要如果我從數組中選擇一個元素,它不會再選擇它 – ray 2012-03-29 11:02:23

回答

0

您可以填寫一個(如果你並不需要太多的數字)ArrayList<Integer>序號爲0 - 3。然後你使用Random.nextInt(list.size())獲取隨機索引,從列表中獲取數字,並在您的索引處獲取removeAt條目。

+0

ArrayList中沒有removeAt方法,可以放一些代碼,我已經嘗試2小時解決它謝謝 – ray 2012-03-29 11:09:05

+0

對不起,它只是被稱爲'刪除(索引)'。 – Neet 2012-03-29 11:18:12

+0

下面是一個例子:http://pastebin.com/ybLcnhYz – Neet 2012-03-29 11:22:16

8

您正在有效地查找從0n-1的整數的隨機排列。

你可以把這一數字從0n-1ArrayList,然後在名單上調用Collections.shuffle(),然後從列表中逐一獲取的數字:與發生的所有排列

final int n = 4; 
    final ArrayList<Integer> arr = new ArrayList<Integer>(n); 
    for (int i = 0; i < n; i++) { 
     arr.add(i); 
    } 
    Collections.shuffle(arr); 
    for (Integer val : arr) { 
     System.out.println(val); 
    } 

Collectons.shuffle()保證同等可能性。

如果你願意,你可以封裝此爲Iterable

public class ChooseUnique implements Iterable<Integer> { 

     private final ArrayList<Integer> arr; 

     public ChooseUnique(int n) { 
      arr = new ArrayList<Integer>(n); 
      for (int i = 0; i < n; i++) { 
       arr.add(i); 
      } 
      Collections.shuffle(arr); 
     } 

     public Iterator iterator() { 
      return arr.iterator(); 
     } 
    } 

當你遍歷這個類的一個實例,它會產生一個隨機排列:

ChooseUnique ch = new ChooseUnique(4); 
    for (int val : ch) { 
     System.out.println(val); 
    } 

在一個特定的運行,這打印出1 0 2 3

+0

謝謝,但這並沒有解決它,洗牌並不能確保唯一沒有 – ray 2012-03-29 10:58:22

+1

@ray:其實,它的確如此。每個數字只出現在最終列表中一次。你有沒有試過運行代碼? – NPE 2012-03-29 10:59:29

+1

男士我很感激,非常感謝你 – ray 2012-03-29 11:16:53

0

如果你在某種類型的數組中有你的範圍,那麼只需在數組長度上隨機使用。

例如,如果您有一個名爲range的int數組。然後你可以使用:

java.utils.Random randomGenarator = new java.utils.Random(); 
return range[randomGenarator.nextInt(range.length)]; 
+0

這不是一個獨特的數字感謝壽 – ray 2012-03-29 11:04:34

相關問題