【问题标题】:Add unique random numbers to an integer array将唯一随机数添加到整数数组
【发布时间】:2014-07-29 09:26:01
【问题描述】:

我为整数创建了一个 ArrayList,我想用 200 个数字填充它。每个数字可以在 0 到 1023 之间的范围内。

所以我写了这段代码:

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 循环将向“值”ArrayList 添加 200 个随机数,从 0 到 1023。现在我的问题是我希望数组只有唯一的数字。如何告诉 Random 类不要生成 ArrayList 中已经存在的任何数字?

【问题讨论】:

标签: java arrays arraylist


【解决方案1】:

我要做的是创建一个由 1,2,3,...,1023 组成的 1023 int 数组。然后你把它洗牌,你只取前 200 个词:

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

Collections.shuffle(ints);

按照@Bohemian♦ 的建议进行编辑

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

【讨论】:

  • 在第一个循环后丢失所有内容并使用 List.subList() 代替:ints = ints.subList(0, START_AMOUNT);
  • 我不想犯错,因为我记不清列表操作。所以这行得通,他有这个想法,但是是的,子列表看起来很不错。
  • 不错的主意,我记得做过类似的事情,谢谢!
【解决方案2】:
A Set is a Collection that cannot contain duplicate elements. 
It models the mathematical set abstraction. 
The Set interface contains only methods inherited from Collection 
and adds the restriction that duplicate elements are prohibited. 

因此,

public boolean add(E e)
  Adds the specified element to this set if it is not already present. 
  [...]
  If this set already contains the element, 
      the call leaves the set unchanged and returns false.

因此,我要做的是使用一个 Set,然后将它们添加到列表中:

List<Integer> values = new ArrayList<Integer>();
Set<Integer> set = new HashSet<Integer>();
while(set.size() < 200) 
{
    set.add(rand.nextInt(1024)); 
}
values.addAll(set);

【讨论】:

  • 我同意,你应该使用一组以避免重复。
【解决方案3】:

使用集合:

Random rand = new Random();
Set<Integer> values = new HashSet<Integer>();
final int START_AMOUNT = 200;

while(values.size() < START_AMOUNT) { 
    values.add(rand.nextInt(1024));      
}
List<Integer> uniqueList = new ArrayList<Integer>(values);
System.out.println(uniqueList);

【讨论】:

  • 我快了7秒,呵呵。
  • 使用 Set 和其他 List 有什么区别?
  • 当您尝试使用 add() 将元素添加到 Set 中时,该元素已包含在 Set 中,那么 add() 方法将返回 false 并且不添加重复元素。
  • 见上面的Zhuinden回答。 Set 不能包含重复项。
【解决方案4】:

您还可以在每次要添加一个时检查 ArrayList 是否包含给定的随机数。

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

int START_AMOUNT = 200;

for(int i = 0; i < START_AMOUNT; i++) {

  r = rand.nextInt(1024);
  If !values.contains(r) {
    values.add(r);
  } else {
   i--;
  }

}

虽然我认为 Kabulan0lak 的答案如果重要的话会更有效。

【讨论】:

    猜你喜欢
    • 2020-10-18
    • 1970-01-01
    • 2013-11-20
    • 1970-01-01
    • 2010-12-09
    • 2016-07-03
    • 2013-09-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多