gpt4 book ai didi

Android,随机不会连续两次重复相同的数字

转载 作者:行者123 更新时间:2023-11-29 20:57:22 25 4
gpt4 key购买 nike

我需要用整数填充一个向量,但我遇到了一些麻烦,我需要用随机数填充它,但不能连续两个数字。 (例如,不是这样的:1,4,4,3,5,9)我制作了这段代码,但效果不佳:

  • @第一次 loja=1;
  • 但直到比赛结束:loja++;
  • int[] con;

随机方法:

private int nasiqim (int max){
Random nasiqimi = new Random();
int i = 0;
i=nasiqimi.nextInt(max);
return i;
}

工作代码:

    int i;
con = new int [loja];
for (i=0; i<loja; i++)
{
con[i] = nasiqim(8);
if(i>0){
while(con[i]==con[i-1])
{
con[i] =nasiqim(8);
}
}
i++;
}

结果是这样的:

  1. 1
  2. 1,4
  3. 1,4,1
  4. 1,4,1,4
  5. 1,4,1,4,1
  6. 5,3,5,3,5,3
  7. 5,3,5,3,5,3,5

这不是我需要的,我需要真正随机的数字,而不是像这样,如果列表是这样的,那就太好了:1,5,6,7,3,0,2,4,1,0,2,3...

谢谢!!

最佳答案

private int[]           con         = null;

private final Random nasiqimi = new Random();

/**
* Test run random.
*/
@Test
public void testRunRandom() {
int loja = 10;
con = new int[loja];
for (int i = 0; i < loja; i++) {
int nextRandom = 0;
while (true) {
nextRandom = nasiqim(8);
if (i == 0 || con[i - 1] != nextRandom) {
con[i] = nextRandom;
break;
}
}
}

}

/**
* Gets the random.
*
* @param max the max
* @return the random
*/
private int nasiqim(int max) {
return nasiqimi.nextInt(max);
}

关于Android,随机不会连续两次重复相同的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27237433/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com