由于第一个有 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(); }
}