整数パラメータ (1 から 100 まで) を使用して後で呼び出すことができる関数を作成したいと考えていました。これにより、ランダムに整数 0、1、または 2 が得られますが、連続して 2 つになることはありません。
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class UniqueRandomObjectSelector {
//Goal is to select objects from a bucket randomly with teh condition that
//no two selections in a row would be same
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
System.out.println(i + "th random Object is " + selectObject(i) + " ");
}
}
//Pick the object from the pool of 3 . e.g. the bucket contains the numbers 1, 2 and 3
private static int PickObject(int j) {
Random rand = new Random(getSeed());
//Find i-1 wala number
for (int i = 1; i < j; i++) {
rand.nextInt(3);
}
return rand.nextInt(3);
}
//Fixed seed so that random number generation sequence is same
static long getSeed() {
return 11231;
}
static int selectObject(int index) {
//Holds the sequence of Objects
List<Integer> list = new ArrayList<>();
int prev = -999;
int i = 1;
//Keep generating the sequence till we have the requested index of objects
while (list.size() <= index) {
//Get a random number from fixed seed
int ranNum = PickObject(i);
//Check if this was same as previous
while (prev == ranNum) {
ranNum = PickObject(++i);
}
prev = ranNum;
list.add(ranNum);
i++;
}
return (list.get(index));
}
}
これを単純化できますか? 使用しているループが多すぎるようです。