Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.Random producing the same random number

Tags:

random

f#

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
like image 273
McGreggus Avatar asked May 26 '19 05:05

McGreggus


People also ask

Can you generate the same random numbers everytime?

random seed() example to generate the same random number every time. If you want to generate the same number every time, you need to pass the same seed value before calling any other random module function.

Is it possible to use a randomly generated value again in Tosca?

You can use Value Expressions to generate random values, for instance if you want to generate passwords for new users: integer values. decimals. random strings.

Why programming random is not random?

Software-generated random numbers only are pseudorandom. They are not truly random because the computer uses an algorithm based on a distribution, and are not secure because they rely on deterministic, predictable algorithms.


2 Answers

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 ()

like image 194
nilekirk Avatar answered Sep 21 '22 06:09

nilekirk


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())

like image 36
Scott Hutchinson Avatar answered Sep 21 '22 06:09

Scott Hutchinson