仅使用数组生成无重复的随机数

时间:2016-07-23 22:51:17

标签: java

我想用X0的随机整数填充大小为X的数组,但没有重复。问题是我必须只使用数组来存储int,没有ArrayList的集合。我该如何实施呢?

我不明白为什么我似乎无法得到这个。但这是我最近的一些代码填充列表但允许重复。

System.out.print("Zero up to but excluding ");
int limit = scanner.nextInt();

// create index the size of the limit
int [] index = new int[limit];

for(int fill=0;fill<limit;fill+=1){
    index[fill] = (limit);
}

int randomNumber = 0;
Random rand = new Random();
int [] randoms = new int[limit];
boolean flag = true;

// CODE TO NOT PRINT DOUBLES
for (int z=0;z<limit;z+=1){
    randomNumber = rand.nextInt(limit);
    int i=0;
    while (i<limit){
        if (index[i] == randomNumber){
            flag = true;
        }
        else {
            flag = false;
            break;
        }
        i+=1;
    }
    if (flag == false){
        randoms[z] = randomNumber;
        index[z] = randomNumber;
    }
}
System.out.println("Randoms: "+java.util.Arrays.toString(randoms));

4 个答案:

答案 0 :(得分:4)

以下是一种方法:

  1. 创建一个长度为N
  2. 的数组
  3. 从0填充到N-1
  4. 运行for循环并随机交换2个索引
  5. 代码:

    // Step 1
    int N = 10;
    int[] array = new int[N];
    
    // Step 2
    for(int i=0; i < N; i++)
       array[i] = i;
    
    // Step 3
    for(int i=0; i < N; i++) {
       int randIndex = (int) (Math.random() * N);
       int tmp = array[i];
       array[i] = array[randIndex];
       array[randIndex] = tmp;
    }
    

答案 1 :(得分:0)

为什么不改变问题来改组整数数组。首先使用数字0到X单调填充数组。然后使用Random()函数选择一个X数字与位置0中的数字进行交换。重复任意次数。完成。

答案 2 :(得分:0)

考虑使用另一个填充元素的数组,顺序从0到X.然后,使用此数组,随机播放元素。你是怎么做到这一点的?使用循环遍历数组的每个元素,并为每次迭代选择一个从0到array.length - 1的随机数,并在您当前所在的索引和随机索引处切换元素。这就是它的样子,

在你的主要内容中,你可以通过这样做来初始化数组,

int[] arr = new int[10];//10 can be interchangeable with any other number
for(int i = 0; i < arr.length; i++){
    arr[i] = i;
}
shuffleArray(arr);

shuffle方法看起来像这样,

public int[] shuffleArray(int[] arr){
    Random rand = new Random();
    for(int i = 0; i < arr.length; i++){
        int r = rand.nextInt(arr.length);//generate a random number from 0 to X
        int k = arr[i];
        arr[i] = arr[r];
        arr[r] = k;
    }
}

答案 3 :(得分:0)

这是你的错误:

  while (i<limit){
    if (index[i] == randomNumber){
      flag = true;
    }
    else {flag = false;break;}  <--- rest of the array is skipped
    i+=1;
  }

生成一个新数字后,你开始检查是否相等,但是一旦你发现randomNumber!= index [i](else语句),你就会突破。看看这个:实际数组是3,4,5,1你的新数字是5,你将它与3进行比较只是为了发现它们不同,所以flag设置为false并且发生爆发。

相关问题