System.Random().Next()返回相同的结果

Nic*_*ner 3 .net f#

我试图改组列表的元素:

(* 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
Run Code Online (Sandbox Code Playgroud)

但是,这总是items以相同的顺序返回,因为:

> 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)]
Run Code Online (Sandbox Code Playgroud)

为什么System.Random().Next()每次调用都会返回相同的值?是因为连续的电话是按时间顺序太靠近了吗?或者我是否以其他方式误导了API?

(注意:这个答案对我来说很好,但我很好奇为什么会出现这种行为.)

Joa*_*son 9

最好用System.Random()的默认构造函数手册来解释;

默认种子值源自系统时钟并具有有限的分辨率.因此,通过调用默认构造函数紧密连续创建的不同Random对象将具有相同的默认种子值,因此将生成相同的随机数集.