I'm trying to shuffle the elements of a list:
(* Returns a list with the same elements as the original but in randomized order *)
let shuffle items =
items
|> List.map (fun x -> (x, System.Random().Next()))
|> List.sortBy snd
|> List.map fst
However, this just always returns items
in the same order, because:
> List.map (fun x -> x, System.Random().Next()) [1; 2; 3];;
val it : (int * int) list = [(1, 728974863); (2, 728974863); (3, 728974863)]
> List.map (fun x -> x, System.Random().Next()) [1; 2; 3];;
val it : (int * int) list =
[(1, 1768690982); (2, 1768690982); (3, 1768690982)]
> List.map (fun x -> x, System.Random().Next()) [1; 2; 3];;
val it : (int * int) list = [(1, 262031538); (2, 262031538); (3, 262031538)]
Why is System.Random().Next()
always returning the same value in each call? Is it because the successive calls are chronologically too close together? Or am I misuing the API in some other way?
(Note: this answer works fine for me, but I'm curious about why this behavior shows up.)