mirror of
https://github.com/c-cube/ocaml-containers.git
synced 2025-12-06 11:15:31 -05:00
CCRandom: Add sample_without_replacement
This commit is contained in:
parent
1c6c4d846e
commit
08403bac9f
2 changed files with 22 additions and 0 deletions
|
|
@ -78,6 +78,20 @@ let replicate n g st =
|
|||
if n = 0 then acc else aux (g st :: acc) (n-1)
|
||||
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
|
||||
|
||||
exception SplitFail
|
||||
|
|
|
|||
|
|
@ -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
|
||||
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
|
||||
(** Build random lists from lists of random generators
|
||||
@since 0.4 *)
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue