Why does the rand() return always the same number?

前端 未结 3 1758
没有蜡笔的小新
没有蜡笔的小新 2021-01-07 16:07

I am using

rand(200)

in my Rails application. When I run it in console it always returns random number, but if I use it in appl

相关标签:
3条回答
  • 2021-01-07 16:13

    Try Random.rand(). For example

    Random.rand(200)
    

    Or if you're working with an array you could use sample.

    [*1..200].sample
    
    0 讨论(0)
  • 2021-01-07 16:30

    Simple pseudo-random number generators actually generate a fixed sequence of numbers. The particular sequence you get is determined by the initial "seed" value. My suspicion is that you are always getting the first number in the same sequence. Therefore I suggest we try to change the sequence by calling srand every time before calling rand, thus changing the seed value every time. The docs explain that, when called without a parameter, srand generates a new seed based on current circumstances (e.g. the time on the clock). Thus you should get a difference sequence and hence a different random number:

    srand
    rand(200)
    

    Now, you may ask - why are you always getting the same sequence? I have no idea! As someone else suggested in one of the comments, the behavior you are seeing is the behavior one would expect if you had other code, anywhere, that calls srand with the same, fixed value every time. So it might be good to look for that.

    0 讨论(0)
  • 2021-01-07 16:39

    rand(200) is run once and that value is assigned to your index variable. So 'index' will always be that number.

    If you want index to change, you will need to continually run rand on it.

    Here's a simple way to do that:

    def randomIndex(num)
      index = rand(num)
      return index
    end
    
    randomIndex(200)
    => // this value will change
    
    0 讨论(0)
提交回复
热议问题