本文介绍了添加独特的随机数的整数数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经为这,我想,以填补200号整数一个ArrayList。每个数字都可以是一个范围内0和1023之间。

I've created an ArrayList for integers which I would like to fill with 200 numbers. Each number can be within a range between 0 and 1023.

所以我写这code:

Random rand = new Random();
ArrayList<Integer> values = new ArrayList<Integer>();

int START_AMOUNT = 200;

for(int i = 0; i < START_AMOUNT; 

  values.add(rand.nextInt(1024));      

}

如您所看到的,for循环将增加200随机数的价值的ArrayList,从0到1023。现在我的问题是,我想向数组只有唯一的数字。我怎么能告诉Random类不产生已经是存在的ArrayList中?

As You might see, the for-loop will add 200 random numbers to the "values" ArrayList, from 0 to 1023. Now my problem is that I want the Array to have only unique numbers. How can I tell the Random class not to generate any numbers that already are existent in the ArrayList?

推荐答案

我会做的是建立由1,2,3,...,1023由1023整数的数组。然后你得洗它,你只需要200第一项:

What I'd do is creating an array of 1023 int composed by 1,2,3,...,1023. Then you shuffle it, and you take only the 200 first terms :

List<Integer> ints = new ArrayList<Integer>();
for(int i = 1; i <= 1023; i++)
{
    ints.add(i);
}

Collections.shuffle(ints);

:由建议编辑@波西米亚♦

List<Integer> result = ints.subList(0,200);

这篇关于添加独特的随机数的整数数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 11:38