CCRandom: Add sample_without_replacement

This commit is contained in:
octachron 2015-11-11 23:36:55 +02:00
parent 1c6c4d846e
commit 08403bac9f
2 changed files with 22 additions and 0 deletions

View file

@ -78,6 +78,20 @@ let replicate n g st =
if n = 0 then acc else aux (g st :: acc) (n-1) if n = 0 then acc else aux (g st :: acc) (n-1)
in aux [] n in aux [] n
(* Sample without replacement using rejection sampling. *)
let sample_without_replacement (type elt) ?(compare=compare) k (rng:elt t) st=
let module S = Set.Make(struct type t=elt let compare = compare end) in
let rec aux s k =
if k <= 0 then
S.elements s
else
let x = rng st in
if S.mem x s then
aux s k
else
aux (S.add x s) (k-1) in
aux S.empty k
let list_seq l st = List.map (fun f -> f st) l let list_seq l st = List.map (fun f -> f st) l
exception SplitFail exception SplitFail

View file

@ -76,6 +76,14 @@ val replicate : int -> 'a t -> 'a list t
(** [replicate n g] makes a list of [n] elements which are all generated (** [replicate n g] makes a list of [n] elements which are all generated
randomly using [g] *) randomly using [g] *)
val sample_without_replacement:
?compare:('a -> 'a -> int) -> int -> 'a t -> 'a list t
(** [sample_without_replacement n g] makes a list of [n] elements which are all
generated randomly using [g] with the added constraint that none of the generated
random values are equal
@since 0.15
*)
val list_seq : 'a t list -> 'a list t val list_seq : 'a t list -> 'a list t
(** Build random lists from lists of random generators (** Build random lists from lists of random generators
@since 0.4 *) @since 0.4 *)