使用collection.shuffle(),並選擇指定大小的子列表,或者把你的價值觀在一個列表,並在指數
found.add (list.remove (random.nextInt (list.size()));
爲X次刪除元素。在每一步中,列表的大小都會減小,並且沒有元素會出現兩次。
但是,對於非常大的範圍 - 可以說有效長期的範圍,建立一個列表來洗牌或從中挑選值是不合適的。
因此,創建一個Set,並選擇隨機值,將它們添加到列表中,直到set.size()等於您需要的大小。
Runnable的例子:
import java.util.*;
public class Empty {
static Random random = new Random();
public static void main (String args [])
{
show (pick (10, 100));
show (securePick (10, 100000));
}
static public List <Integer> pick (int n, int max) {
List <Integer> result = new ArrayList <Integer>();
List <Integer> range = new ArrayList <Integer> (max);
for (int i= 0; i < max; ++i)
range.add (i);
for (int i= 0; i < n; ++i)
result.add (range.remove (random.nextInt (range.size())));
return result;
}
static public Set <Integer> securePick (int n, int max) {
Set <Integer> result = new HashSet <Integer>();
while (result.size() < n)
result.add (random.nextInt (max));
return result; // <Integer>
}
public static void show (List <Integer> liste)
{
System.out.print ("[");
for (int i : liste)
System.out.print (i + ", ");
System.out.println ("\b\b]");
}
public static void show (Set <Integer> liste)
{
System.out.print ("[");
for (int i : liste)
System.out.print (i + ", ");
System.out.println ("\b\b]");
}
}
使用HashSet的,如果該號碼不在集合,使用它,否則再生? – DarthVader
一個不相關的技巧:你可以使用ArrayList而不是你現在正在用int數組做什麼。 –
AHungerArtist
@DarthVader沒有哈希集(與任何一般哈希相同)自動銷燬重複出現? – 2012-05-12 21:45:24