2012-04-01 112 views
1

如何選擇只有一張圖片無法重複?隨機顏色序列

我嘗試這樣做:

我使用隨機,我想刪除選定的圖片

String[] picture = { "blue", "white", "red", "yellow" }; 

    int number_picture1; 

// Random function to find a random picture 

    Random ran = new Random(); 

    number_picture1 = ran.nextInt(picture.length); 

System.out.println(picture[number_picture1]); 

// There is still posibility to chose the same picture 

    int number_picture2; 

    number_picture2 = ran.nextInt(picture.length); 

System.out.println(picture[number_picture2]); 

回答

6

最簡單的方法是使用一個List 存儲你的元素,並使用Collections.shuffle() - 然後迭代地獲取元素。

shuffle產生列表的隨機排列,所以選擇項目迭代地給你相同的概率來選擇任何排序,這似乎正是你在之後。

代碼卡:

String[] picture = { "blue", "white", "red", "yellow" }; 
//get a list out of your array: 
List<String> picturesList = Arrays.asList(picture); 
//shuffle the list: 
Collections.shuffle(picturesList); 
//first picture is the first element in list: 
String pictureOne = picturesList.get(0); 
System.out.println(pictureOne); 
//2nd picture is the 2nd element in list: 
String pictureTwo = picturesList.get(1); 
System.out.println(pictureTwo); 
... 

(1)最簡單的方式來獲得一個數組列表中使用Arrays.asList()

+0

我得到錯誤//類型java.awt.List不帶參數。 – 2012-04-01 12:51:56

+3

@LukaToni不要使用'java.awt.List',你需要使用['java.util.List'](http://docs.oracle.com/javase/6/docs/api/java/util /List.html)。請參閱此界面的文檔。 – amit 2012-04-01 12:53:07

2

使用一個ListSet而不是數組,然後從它每次選擇之後移除所選圖片

import java.util.List; 
import java.util.Arrays; 

List<String> pictures = Arrays.asList("blue","white","red","yellow"); 
int number_picture1; 

number_picture1=ran.nextInt(pictures.size()); 
System.out.println (pictures.remove(number_picture1)); 

int number_picture2; 

number_picture2=ran.nextInt(pictures.size()); 
... 
+0

我必須導入工作清單? – 2012-04-01 12:38:38

+0

@LukaToni,看我的更新。 – 2012-04-01 12:45:29

+1

@LukaToni沒有冒犯,但如果您必須要求我建議您先閱讀一些基本的Java書籍。再一次,沒有冒犯的意思。 – 2012-04-01 13:38:13

1

雖然你沒有給的ran聲明,我想這是標準的JDK隨機數生成器。

那個人不能保證任何不同的號碼被選中兩次。在一個真正的隨機算法,這將是一個相當奇怪的保證。

解決此問題的一種方法是將與您的選擇對應的數字放入鏈接列表(此處爲{0,1,2,3})。然後選擇一個0到你列表大小的隨機整數(這裏是3)。假設你得到'2',然後從列表中刪除第二個元素,使得{0,1,3}。下一次選擇一個介於0和2之間的數字。如果現在再次獲得'2',則再次刪除第二個現在爲'3'的元素。等

3

使用集合是一個更好的選擇檢索和刪除。使用數組,可以跟蹤已經選擇的索引。另外,如果選擇的數量大於數組的長度,則相應地拋出異常。