4

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?

Aviv
  • 58
  • 5
  • I would suggest "Searching" before you ask. http://stackoverflow.com/questions/2019417/access-random-item-in-list – Jonas Fjeld Dec 14 '16 at 09:15
  • I would do similar to your solution but just put them in an array and generate a random number between 0-array.size and use that as an index. – nesohc Dec 14 '16 at 09:16
  • The "best" solution to this problem will depend on the value of `x`. If it is high and the number of different values is also hight, and memory usage is a problem, then a more memory-efficient solution may be warranted. Otherwise, just put all the numbers (including 'x' copies) into an array and shuffle it. – Matthew Watson Dec 14 '16 at 09:20
  • @nesohc well, i don't know the amount of different numbers i get, that's why i used arrayList. – Aviv Dec 14 '16 at 10:12

3 Answers3

7

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
Eran
  • 387,369
  • 54
  • 702
  • 768
0

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()
Ajay Pawar
  • 179
  • 6
0

Another Easiest way is to use Windows PowerShell

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

That't it

Ajay Pawar
  • 179
  • 6