生成列表 OCaml 元素的随机排列
Generate a random permutation of the elements of a list OCaml
我想生成列表元素的随机排列,
示例:
listString = ["a"; "b"; "c"; "d"; "e"; "f"]
我想要这样的东西:
result = ["a"; "e"; "f"; "b"; "d"; "c"]
但是每次调用该函数时都会发生变化。
所以当我第二次调用该函数时 return 类似于:
result = ["c"; "d"; "b"; "f"; "e"; "a"]
我找到了解决方案:
let shuffle d = begin
Random.self_init ();
let nd = List.map (fun c -> (Random.bits (), c)) d in
let sond = List.sort compare nd in
List.map snd sond
end
行Random.self_init();使用以系统相关方式选择的随机种子初始化生成器。
我想生成列表元素的随机排列, 示例:
listString = ["a"; "b"; "c"; "d"; "e"; "f"]
我想要这样的东西:
result = ["a"; "e"; "f"; "b"; "d"; "c"]
但是每次调用该函数时都会发生变化。 所以当我第二次调用该函数时 return 类似于:
result = ["c"; "d"; "b"; "f"; "e"; "a"]
我找到了解决方案:
let shuffle d = begin
Random.self_init ();
let nd = List.map (fun c -> (Random.bits (), c)) d in
let sond = List.sort compare nd in
List.map snd sond
end
行Random.self_init();使用以系统相关方式选择的随机种子初始化生成器。