我想编写一个函数,随后可以用一个整数参数(从 1 到 100 开始)调用它,它随机给我一个整数 0、1 或 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));
}
}
这可以简化吗,看起来我使用了太多循环。