mercredi 23 octobre 2019

Just wan't choose some random elements of a list and put and return them in OCaml

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!

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

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



Aucun commentaire:

Enregistrer un commentaire