F # getting a list of random numbers

I am trying to populate a list with random numbers, and I have a diffculty getting some random numbers. What I have now is printing a random number 10 times, I want to print 10 different random numbers

let a = (new System.Random()).Next(1, 1000) let listOfSquares = [ for i in 1 .. 10->a] printfn "%A" listOfSquares 

any tips or suggestions?

+13
source share
6 answers
 let genRandomNumbers count = let rnd = System.Random() List.init count (fun _ -> rnd.Next ()) let l = genRandomNumbers 10 printfn "%A" l 
+21
source

Your code just gets one random number and uses it ten times.

This extension method may be useful:

 type System.Random with /// Generates an infinite sequence of random numbers within the given range. member this.GetValues(minValue, maxValue) = Seq.initInfinite (fun _ -> this.Next(minValue, maxValue)) 

Then you can use it as follows:

 let r = System.Random() let nums = r.GetValues(1, 1000) |> Seq.take 10 
+36
source

When I write a random distributor, I like to use the same random number generator for every dispenser call. You can do this in F # with closure (a combination of Joel and ildjarn answers).

Example:

 let randomWord = let R = System.Random() fun n -> System.String [|for _ in 1..n -> R.Next(26) + 97 |> char|] 

Thus, one instance of Random is “baked” into the function, reusing it with every call.

+3
source

You may find this article helpful: http://brunoreis.com/tech/generate-random-int-list/

+2
source

I think you need to be careful how to initialize System.Random, since it uses the current time as a seed. One instance should be enough for the entire application. Injecting random numbers into a function has the advantage that you can use a fixed seed and play with randomness, for example, to test your logic.

 let rnd = System.Random() let genRandomNumbers count random = List.init count (fun _ -> random.Next ()) let l = genRandomNumbers 10 printfn "%A" l 
0
source

There are two problems:

1) In F #, functions must be clean , so a function with no arguments is considered the final value.

To declare an impure function "without arguments", let it take one argument of type unit

 let a () = (new System.Random()).Next(1, 1000) 

and name it passing the block argument

 let list = [ for i in 1 .. 10 -> a () ] 

A source

2) A new instance of System.Random() is created each time a is called. This results in identical numbers. To fix this, create an instance only once.

 let random = new System.Random() let a () = random.Next(1, 1000) let list = [ for i in 1 .. 10 -> a ()] 

This does not apply to F #, read the C # explanation for a better understanding.

0
source

Source: https://habr.com/ru/post/888564/


All Articles