0

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...

Community
  • 1
  • 1
Tim
  • 1,749
  • 3
  • 24
  • 48
  • 5
    What have your tried so far? What particular problems did you encounter? – Fyodor Soikin Mar 30 '16 at 16:16
  • Well using your test they are all different. – John Palmer Mar 31 '16 at 07:34
  • The numbers I get when I run your code are different - `[27; 88; 77; 5; 90; 23; 13; 14; 47; 81]`. – Enigmativity Mar 31 '16 at 07:36
  • it's random, they can be equals. And I had a case where it was equal. I need a way to check that the number are not many times in the list. This is the list I had : [22; 12; 31; 12; 23; 74; 44; 28; 57; 51]. With an OO language, I would get a random number, check that not present and had it, if already present in the list, i do the random again. – Tim Mar 31 '16 at 07:46
  • Watch out with `System.Random`. Bots its seeding and distribution are broken; calling the above `getRandomNumbers` multiple times may result in identically seeded RNGs and therefore identical sequences. – Vandroiy Mar 31 '16 at 11:28
  • sure, but what i need is to have different numbers in the list, like a lottery – Tim Mar 31 '16 at 12:10
  • @Tim: the word you're looking for is "unique" then. – scrwtp Apr 04 '16 at 13:24
  • changed. Do you have a solution for this ? thanks – Tim Apr 04 '16 at 14:03

1 Answers1

2

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!

Ringil
  • 6,277
  • 2
  • 23
  • 37