McGreggus
McGreggus

Reputation: 345

System.Random producing the same random number

Despite the Random generator only being created once, the output is always the same random result (for all three test outputs).

A test snippet from a slightly larger script:

   let myRandGen = System.Random()
   let getRandomObject = 
      let options = [|"Bob"; "Jim"; "Jane"|]
      let randIndex  = myRandGen.Next(options.Length) 
      options.[randIndex] 

   printfn "New one: %s" getRandomObject
   printfn "New two: %s" getRandomObject
   printfn "New three: %s" getRandomObject

I need the output to be random for each call, which it currently isn't.

Example output:

New one: Jane
New two: Jane
New three: Jane

Upvotes: 5

Views: 292

Answers (3)

Quijibo
Quijibo

Reputation: 333

You generated your random number once, which doesn't change throughout the whole program. To have a new random value after every use, you must re-initialize the random value.

Upvotes: 0

Scott Hutchinson
Scott Hutchinson

Reputation: 1721

This works for me:

   let myRandGen = System.Random()
   let getRandomObject () = 
      let options = [|"Bob"; "Jim"; "Jane"|]
      let randIndex  = myRandGen.Next(options.Length) 
      options.[randIndex] 

   printfn "New one: %s" (getRandomObject())
   printfn "New two: %s" (getRandomObject())
   printfn "New three: %s" (getRandomObject())

Upvotes: 4

nilekirk
nilekirk

Reputation: 2393

Your getRandomObject is a value. It is evaluated once. To fix this, make getRandomObject a function:

let getRandomObject () = 
  let options = [|"Bob"; "Jim"; "Jane"|]
  let randIndex  = myRandGen.Next(options.Length) 
  options.[randIndex]

and call it like so: getRandomObject ()

Upvotes: 12

Related Questions