I'm trying to learn F# but I'm stuck with a very simple thing.
I would like to create a list with uniques random values that I can display on a console. Let say Random from 1 to 100 and 10 elements in the list.
I've seen here this code F# getting a list of random numbers :
let genRandomNumbers count =
let rnd = System.Random()
List.init count (fun _ -> rnd.Next (1, 100))
let l = genRandomNumbers 10
printfn "%A" l
But how can I make theses numbers be differents ? This is not exactly a duplicate question because I don't find a way to be sure that each number is unique ; Random.Next can generate same numbers...
Here's a very simple solution:
let genRandomNumbers count =
let rnd = System.Random()
let initial = Seq.initInfinite (fun _ -> rnd.Next (1, 100))
initial
|> Seq.distinct
|> Seq.take(count)
|> Seq.toList
Note the Seq.distinct
does exactly what you want to get the unique values. Also note that you'll get an issue if you try to get a count larger than 99 because there aren't that many distinct values between 1 and 99!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.