Quantcast
Channel: Active questions tagged ocaml - Stack Overflow
Viewing all articles
Browse latest Browse all 591

Just want choose some random elements of a list and return them in OCaml

$
0
0

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 ;;

Viewing all articles
Browse latest Browse all 591

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>