How to generate a random number from a pool of numbers that do not follow each other

I have 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 the “element” of two integers (num, numOfAppearnces).

I created a pool of "elements" in an arrayList, and then generated random numbers from 0 to list.size and got the number stored in a random index. when numOfAppearances decreased to 0, I removed this item from the list.

My question is, is there another elegant solution for generating a random number, and not out of range?

+4
source share
3 answers

, , .

:

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)):

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
+6

Python

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

genRNum()
0

Another easy way is to use Windows PowerShell

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

It is he

0
source

Source: https://habr.com/ru/post/1663723/


All Articles