how to generate a random number from a pool of number who aren't following each other

后端 未结 3 761
伪装坚强ぢ
伪装坚强ぢ 2021-01-19 06:54

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 \"el

相关标签:
3条回答
  • 2021-01-19 07:37

    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
    
    0 讨论(0)
  • 2021-01-19 07:43

    Another Easiest way is to use Windows PowerShell

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

    That't it

    0 讨论(0)
  • 2021-01-19 07:52

    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()
    
    0 讨论(0)
提交回复
热议问题