1

I've been trying to create a simple card game in F#, i have created a simple randomizer function using system.Random.


type card = int
type deck = card list
let rand : int -> int = let rnd = System.Random ()
                        in fun n -> rnd.Next (0 , n )

However my problem is that i don't know how to create a shuffle function deck -> deck,using the rand function.

Any help is wanted.

Marcus F
  • 525
  • 1
  • 3
  • 13
  • You can use a Fisher-Yates shuffle. See: [Can this random number generator logic be simplified?](https://stackoverflow.com/a/33861277/3744182), [Performance of List.permute](https://stackoverflow.com/q/10251744/3744182) [How to Generate A Specific Number of Random Indices for Array Element Removal F#](https://stackoverflow.com/a/17457044/3744182) and http://www.fssnip.net/L/title/Array-shuffle. – dbc Oct 29 '20 at 16:23
  • Also, if you construct a new `Random` every time, subsequent `Random` objects may generate identical results. See: [Random number generator only generating one random number](https://stackoverflow.com/q/767999/3744182) and [Is C# Random Number Generator thread safe?](https://stackoverflow.com/q/3049467/3744182). You will need to translate those answers to f#. – dbc Oct 29 '20 at 16:26

2 Answers2

2

You could sort based on a random value:

let shuffle (d:deck) =
    let rnd = System.Random ()
    d |> List.sortBy(fun _ -> rnd.Next(1, 52) )
AMieres
  • 4,944
  • 1
  • 14
  • 19
0

I would like to point out that the solution proposed by AMieres must not be used if the shuffled deck should be uniformly distributed. See this wikipedia article.

"A variant of the above method that has seen some use in languages that support sorting with user-specified comparison functions is to shuffle a list by sorting it with a comparison function that returns random values. However, this is an extremely bad method: it is very likely to produce highly non-uniform distributions, which in addition depends heavily on the sorting algorithm used."

As an alternative, see this SO answer.