I want to choose n
distinct random elements in a list l
and return them in choose_elements
but I have a StackOverFlow
error for sufficiently large lists!
I tried to use a tail_recursive function choose_elem_aux
in order to do that but I think my condition List.mem
is not efficient enough in term of complexity!I do this normally in other programming languages with a boolean mark array which I mark the index of each random number that is generated in true
!But I can't do this in OCaml because I can't do multiple instruction into an if or else block! like this:
... 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 for large list like:
choose_elements [1...10_000] 7 ;;