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
  • 446
  • 1
  • 2
  • 10
  • 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

1 Answers1

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,766
  • 1
  • 13
  • 17