mirror of
https://github.com/c-cube/ocaml-containers.git
synced 2025-12-08 12:15:32 -05:00
add CCArray.swap
This commit is contained in:
parent
54e12b7f62
commit
d7b90d3ba3
2 changed files with 36 additions and 3 deletions
|
|
@ -468,6 +468,35 @@ let compare cmp a b =
|
||||||
compare CCOrd.compare [| 1; 2; 3 |] [| 1; 2; |] > 0
|
compare CCOrd.compare [| 1; 2; 3 |] [| 1; 2; |] > 0
|
||||||
*)
|
*)
|
||||||
|
|
||||||
|
(* swap elements of array *)
|
||||||
|
let swap a i j =
|
||||||
|
if i<>j then (
|
||||||
|
let tmp = a.(i) in
|
||||||
|
a.(i) <- a.(j);
|
||||||
|
a.(j) <- tmp;
|
||||||
|
)
|
||||||
|
|
||||||
|
(*$T
|
||||||
|
let a = [| 1;2;3 |] in \
|
||||||
|
swap a 0 1; \
|
||||||
|
a = [| 2;1;3 |]
|
||||||
|
let a = [| 1;2;3 |] in \
|
||||||
|
swap a 0 2; \
|
||||||
|
a = [| 3;2;1 |]
|
||||||
|
*)
|
||||||
|
|
||||||
|
(*$QR
|
||||||
|
Q.(array small_int) (fun a ->
|
||||||
|
let b = Array.copy a in
|
||||||
|
for i = 0 to Array.length a-1 do
|
||||||
|
for j = i+1 to Array.length a-1 do
|
||||||
|
swap a i j; done; done;
|
||||||
|
for i = 0 to Array.length a-1 do
|
||||||
|
for j = i+1 to Array.length a-1 do
|
||||||
|
swap a i j; done; done;
|
||||||
|
a=b)
|
||||||
|
*)
|
||||||
|
|
||||||
(* shuffle a[i...j[ using the given int random generator
|
(* shuffle a[i...j[ using the given int random generator
|
||||||
See http://en.wikipedia.org/wiki/Fisher-Yates_shuffle *)
|
See http://en.wikipedia.org/wiki/Fisher-Yates_shuffle *)
|
||||||
let _shuffle _rand_int a i j =
|
let _shuffle _rand_int a i j =
|
||||||
|
|
|
||||||
|
|
@ -23,6 +23,10 @@ val equal : 'a equal -> 'a t equal
|
||||||
|
|
||||||
val compare : 'a ord -> 'a t ord
|
val compare : 'a ord -> 'a t ord
|
||||||
|
|
||||||
|
val swap : 'a t -> int -> int -> unit
|
||||||
|
(** [swap arr i j] swaps elements at indices [i] and [j].
|
||||||
|
@since NEXT_RELEASE *)
|
||||||
|
|
||||||
val get : 'a t -> int -> 'a
|
val get : 'a t -> int -> 'a
|
||||||
|
|
||||||
val get_safe : 'a t -> int -> 'a option
|
val get_safe : 'a t -> int -> 'a option
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue