0

Possible Duplicate:
F# getting a list of random numbers

I'm getting random value from list each time on tick (timer) but I'm getting the same 3 times only then it changes...

the code:

let timer = new DispatcherTimer()
timer.Tick.Add  <| fun _ -> X.Change()
timer.Interval  <- new TimeSpan(0,0,3)    

    member X.Change() = 
        (Seq.nth
            (System.Random().Next(Seq.length actions))
                <| actions)()

Why? I want to get different value each time

Community
  • 1
  • 1
cnd
  • 32,616
  • 62
  • 183
  • 313
  • 1
    This has been asked [so...many...times](https://www.google.com/search?as_q=random+same+value&as_sitesearch=stackoverflow.com%2Fquestions). Please search first. – Daniel Sep 21 '12 at 15:10

1 Answers1

2

I'm not entirely sure about your example, but the general guideline is that you should create one instance of System.Random (or one instance per thread, if you have a multi-threaded application) and then use it multiple times.

Try something like this:

let timer = new DispatcherTimer() 
let rnd = new System.Random()
timer.Tick.Add  <| fun _ -> X.Change() 
timer.Interval  <- new TimeSpan(0,0,3)     

    member X.Change() =  
        (Seq.nth 
            (rnd.Next(Seq.length actions)) 
                <| actions)() 

The Random object is mutable and keeps some state that is used to generate the sequence of random values. When you create a new instance, it initializes the state using current time, so if you create multiple instances at the same time, you'll get the same numbers.

As an aside, if you need to access random elements of actions, then it would be better to store them as an array, because then you can just write:

member X.Change() =  
  actions.[rnd.Next(actions.Length)]()
Tomas Petricek
  • 240,744
  • 19
  • 378
  • 553