how to generate a random number from a pool of num

2019-02-23 08:57发布

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.

My solution was to create a class, let's call it "element", of two integers (num,numOfAppearnces).

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?

标签: java c# random
3条回答
祖国的老花朵
2楼-- · 2019-02-23 09:04

Another Easiest way is to use Windows PowerShell

Get-Random 3,6,7,11,20

That't it

查看更多
We Are One
3楼-- · 2019-02-23 09:09

here is simple Python program

import random
def genRNum():
    numlist = [3,6,7,11,20]
    i = random.randrange(0,4)
    RNum = numlist[i]
    print(RNum)

genRNum()
查看更多
再贱就再见
4楼-- · 2019-02-23 09:10

Yes, there are shorter ways to achieve what you describe.

For example :

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

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
查看更多
登录 后发表回答