如何避免连续两次生成相同的 2 个随机数



我正在尝试使用计时器设置视图的背景颜色,每隔几秒钟更改一次颜色,但由于引用特定颜色的随机数生成两次,因此通常连续设置两次颜色。如何更改代码以避免连续两次生成相同的随机数?

final Runnable runnable = new Runnable() {
@Override
public void run() {
Random rand = new Random();
int n = rand.nextInt(3);
n += 1;

switch (n){
case 1:
colorView.setBackgroundColor(Color.GREEN);
break;
case 2:
colorView.setBackgroundColor(Color.MAGENTA);
break;
case 3:
colorView.setBackgroundColor(Color.CYAN);
break;
}
}
};

唯一的方法是测试旧数字是否等于最新生成的数字。

Random rand = new Random();
int n = rand.nextInt(3);
n += 1;
while (n == oldValue) {
n = rand.nextInt(3);
n += 1;
}
switch (n){
...
}
oldValue = n; //The oldValue should be global

试试这个:

Set<Integer> generated = new HashSet<>();
int randomMax = 3;
final Runnable runnable = new Runnable() {
@Override
public void run() {
Random rand = new Random();
int n = rand.nextInt(randomMax);
while (generated.contains(n) && generated.size() < randomMax) {
n = rand.nextInt(randomMax);
}
if (generated.size() == randomMax) {
throw new Exception("all numbers already generated")
}
generated.add(n);
n += 1;
switch (n){
case 1:
colorView.setBackgroundColor(Color.GREEN);
break;
case 2:
colorView.setBackgroundColor(Color.MAGENTA);
break;
case 3:
colorView.setBackgroundColor(Color.CYAN);
break;
}
}
};

您可以将上次创建的整数存储在变量 'temp' 中,并将其与当前步骤中创建的整数进行比较:

final Runnable runnable = new Runnable() {
@Override
public void run() {
if(tempInt == null){
int tempInt = 0;
int n = 0;
}
Random rand = new Random();
while(n == tempInt){
n = rand.nextInt(3);
n += 1;
}
tempInt = n;
switch (n){
case 1:
colorView.setBackgroundColor(Color.GREEN);
break;
case 2:
colorView.setBackgroundColor(Color.MAGENTA);
break;
case 3:
colorView.setBackgroundColor(Color.CYAN);
break;
}
}

你可以做这样的事情

//set it as a global variable
int previousRandomNumber=0; //set it as 0 for first time
final Runnable runnable = new Runnable() {
@Override
public void run() {
int currentRandomNumber=new Random.nextInt(3);
currentRandomNumber+=1;
while(currentRandomNumber == previousRandomNumber){
currentRandomNumber = new Random.nextInt(3);
currentRandomNumber+=1;
}
/*store the current number as the previous number to check with next the generated number is the same or not*/
previousRandomNumber=currentRandomNumber;
switch (n){
case 1:
colorView.setBackgroundColor(Color.GREEN);
break;
case 2:
colorView.setBackgroundColor(Color.MAGENTA);
break;
case 3:
colorView.setBackgroundColor(Color.CYAN);
break;
}
}
};

最新更新