既然你有N個可能值第一,只有N-1的後續,只是用randInt
可根據您是否是一個不同的觀點是否產生第一個值。試圖對所有迭代使用相同參數的randInt
將導致非平坦分佈。
class NoAdjacentPRNG implements Iterator<Integer> {
private final Random rnd;
private final int range; // 3 to generate numbers in [0, 2).
private Integer last;
NoAdjacentPRNG(Random rnd, int range) {
this.rnd = rnd;
this.range = range;
}
public boolean hasNext() { return true; }
public Integer next() {
int n;
if (last == null) {
// The first time through, there are range possible values.
n = rnd.nextInt(range);
} else {
// There are only range-1 possible values given that the
// last is excluded.
n = rnd.nextInt(range - 1);
// Work around last.
if (n >= last) { ++n; }
}
last = n;
return n;
}
public void remove() { throw new UnsupportedOperationException(); }
}
你怎麼樣產生一個隨機數,並檢查它的與剛剛生成的相同。如果是,則生成一個新的隨機數。重複,直到你得到新的東西。這是基本的編程,沒什麼複雜的。 – jahroy 2013-04-28 18:05:26
你可以用你想控制隨機數範圍的任意數字乘上math.random()的結果(0和1之間的一個值)。 – jahroy 2013-04-28 18:09:43
對不起,如果我迷惑任何人。當我生成一個數字時,我不希望它與前一個生成的數字相同。其他數字都可以。此外,我試着檢查它是否是相同的數字,直到我得到新的東西,但我在代碼中遇到了麻煩。感謝您的幫助傢伙btw :) – 2013-04-28 18:13:13