2011-04-28 43 views
0


是否可以在Java中執行此操作?我想生成一個隨機數,例如給定一個範圍,例如:在1到70之間 - 每次生成隨機數時,它應該從生成結果中排除。
所以[1,70]蘭特= 56(現在56不應當被認爲在下一次)
[1,70] = 63(現在56,63應排除代直到我的代碼運行)隨機數生成和排除生成的數字

+0

複製到一個問題:** [Java的創建隨機數,沒有重複(http://stackoverflow.com/questions/4040001/java-creating-random-numbers-with-no-duplicates)** – lschin 2011-04-28 03:42:39

回答

3

這相當於將包含[1..70]的數組進行混洗,然後逐個處理它們。在Google上查找「洗牌算法」。這裏有一個鏈接http://www.vogella.de/articles/JavaAlgorithmsShuffle/article.html

+1

或者更好地使用JDK附帶的shuffle算法。 http://download.oracle.com/javase/6/docs/api/java/util/Collections.html#shuffle(java.util.List) – 2011-04-28 03:47:43

+0

是的,我忘記了那裏。 – 2011-04-28 03:48:46

1

您可以將範圍填充到數組中並隨機播放數組。這對於非常大的範圍來說效率很低

1

另一個微不足道的選擇是使用HashMaps來跟蹤隨機數。 這是一種快速和骯髒。

HashMap<Integer,Integer> hmRandomNum = new HashMap<Integer,Integer>(); 

Integer a = < generate random number> 

if(hmRandomNum.get(a) == null) 
{ 
    hmRandomNum.put(a,a); 
} 
else 
{ 
    // ignore this random number. this was already selected and present in the hashmap. 
} 

//Iterate depending on how many numbers you want.