问题描述
我有一个数字池(例如{3,6,7,11,20}),我需要每个数字在我的集合中出现x次。
I got a pool of numbers (for example {3,6,7,11,20}) and i need each number to appear in my collection x times.
我的解决方案是创建一个类,让它称之为元素,两个整数(num,numOfAppearnces)。
My solution was to create a class, let's call it "element", of two integers (num,numOfAppearnces).
我创建了一个元素池然后在arrayList中生成一个0到list.size之间的随机数,并得到存储在随机索引中的数字。
当numOfAppearances减少到0时,我从列表中删除了这个元素。
I created a pool of "elements" in arrayList, and then generated a random numbers between 0 to list.size, and got the number stored in the random index.when numOfAppearances decreased to 0, i deleted this element from the list.
我的问题是,是否有任何其他优雅的解决方案来生成随机数,而不是来自一个范围?
my question is, is there any other elegant solution to generate random number, not from a range?
推荐答案
是的,有更短的方式来实现你所描述的。
Yes, there are shorter ways to achieve what you describe.
例如:
Integer[] arr = {3,6,7,11,20};
List<Integer> shuffled = new ArrayList<>();
for (Integer i : arr)
shuffled.addAll (Collections.nCopies(x,i)); // add i to your List x times
Collections.shuffle(shuffled); // shuffle the List to get random order
或者(如果您不想使用 Collections.nCopies(x,i)
):
Or (if you don't want to use Collections.nCopies(x,i)
) :
Integer[] arr = {3,6,7,11,20};
List<Integer> shuffled = new ArrayList<>();
for (int j = 0; j < x; j++)
for (Integer i : arr)
shuffled.add (i);
Collections.shuffle(shuffled); // shuffle the List to get random order
这篇关于如何从不相互跟随的数字池中生成随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!