Non-repetitive random seek in a range Algorithm

后端 未结 7 1657
终归单人心
终归单人心 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:12

    I will pretend you are asking for a solution in R (according to tag). What you're trying to do is sample without replacement. In R, there's a function called sample. Here, I'm sampling a vector of 30 values (1, 2, 3... 30), and once I draw a number, it's not replaced. You can make this reproducible on other machines by setting a seed (see set.seed).

    I ran this a number of times to show the randomness.

    > sample(x = 1:30, size = 10, replace = FALSE)
     [1]  9 16 13 20 12  3  1  5 28  7
    > sample(x = 1:30, size = 10, replace = FALSE)
     [1] 22 11 26 29 20  1  3  6  7 10
    > sample(x = 1:30, size = 10, replace = FALSE)
     [1]  1 11 16  7 22 26  3 25  8  9
    > sample(x = 1:30, size = 10, replace = FALSE)
     [1]  7 17  3 22 21 24 27 12 28  2
    > sample(x = 1:30, size = 10, replace = FALSE)
     [1] 30 21 23  2 27 24  3 18 25 19
    > sample(x = 1:30, size = 10, replace = FALSE)
     [1]  4  6 11 16 26  8 17 22 23 25
    

提交回复
热议问题