【发布时间】:2019-10-23 13:40:45
【问题描述】:
我想在 l 列表中选择 n 不同的随机元素并将它们返回到 choose_elements 但对于足够大的列表我有一个 StackOverFlow 错误!
我尝试使用 tail_recursive 函数 choose_elem_aux 来做到这一点,但我认为我的条件 List.mem 在复杂性方面不够高效!
我通常在其他编程语言中使用布尔标记数组执行此操作,我标记在true 中生成的每个随机数的索引!
但我不能在 OCaml 中执行此操作,因为我无法在 if 或 else 块中执行多条指令!像这样:
... else {
mark[r] =true ;
choose_elem_aux l n mark tmp ;
} ...
let choose l =
nth l (Random.int (List.length l)) ;;
let rec choose_elem_aux l n tmp =
if n=0 then tmp
else
let r=choose l in if List.mem r tmp then
choose_elem_aux l n tmp else choose_elem_aux l (n-1) (r::tmp) ;;
let rec choose_elements l n =
choose_elem_aux l n [] ;;
StackOverflow 用于大型列表,例如:
choose_elements [1...10_000] 7 ;;
【问题讨论】:
标签: list random functional-programming ocaml