Non-repetitive random seek in a range Algorithm

后端 未结 7 1779
终归单人心
终归单人心 2021-01-24 05:36

I\'m looking for an efficient algorithm that produces random values within a range, without repetitions.

In pseudo-code: (in class Rand)

  Rand(long from         


        
7条回答
  •  遇见更好的自我
    2021-01-24 06:03

    You could proceed this way (in python):

    Create a xrange and pick k random element from it and use it as a RanndomGenerator:

    import random
    
    def randomFromTo(FROM,TO,k): #k is the number of sample you want to generate
        m= random.sample(xrange(FROM,TO),k)
        return (i for i in m)
    

    Your Generator will generate all number randomly from FROM to TO and fail when it has generated more than k numbers:

    with this example you would get :

    RandomGenerator=randomFromTo(10,1000000000,12)
    
    for k in range(12): 
        print RandomGenerator.next()
    

    you get

    57625960
    50621599
    2891457
    56292598
    54608718
    45258991
    24112743
    55282480
    28873528
    1120483
    56876700
    98173231
    

提交回复
热议问题