mp2i-info/dm5/lib/lib.ml
2025-12-26 22:33:25 +00:00

132 lines
2.4 KiB
OCaml

(* Exercice 0 *)
let zip ta tb = Array.map2 (fun a b -> a,b) ta tb;;
(* Exercice 1 *)
let tirette t =
let n = Array.length t in
Array.init (n/2) (fun i -> t.(i) + t.(n-i-1))
;;
(* Exercice 2 *)
let quarante_deux t =
let n = Array.length t in
let count = ref 0 in
let i = ref 0 in
while !i < n && !count <= 42 do
if t.(!i) mod 42 = 0 then
count := !count + 1;
i := !i + 42
done;
!count = 42
;;
(* Exercice 3 *)
let croissant t =
let n = Array.length t in
let i = ref 0 in
while !i+1 < n && t.(!i) <= t.(!i+1) do
i := !i+1
done;
!i >= (n-1)
;;
(* Exercice 4 *)
let bitonique t =
let n = Array.length t in
let grows = ref true in
let i = ref 0 in
let res = ref true in
while !res && !i+1 < n do
if !grows then
(if t.(!i) > t.(!i+1) then
grows := false)
else
if t.(!i) < t.(!i+1) then
res := false
done;
!res
;;
(* Exercice 5 *)
let psrn ta tb = Array.fold_left
(fun acc (a,b) -> acc +. (a *. b))
0.
(Array.map2
(fun a b -> a,b)
ta
tb
)
;;
(* Exercice 6 *)
let rotation m =
let nx = Array.length m in
if nx = 0 then [||] else
let ny = Array.length m.(0) in
Array.init_matrix
ny
nx
(fun x y -> m.(y).(ny-x-1))
;;
(* Exercice 7 *)
let plsci t =
let n = Array.length t in
let current_start = ref 0 in
let start = ref 0 in
let max_length = ref (min 1 n) in
for i = 0 to n-1 do
if i+1 = n || t.(i) != t.(i+1) then (
let length = i - !current_start + 1 in
if !max_length < length then (
max_length := length;
start := !current_start
);
current_start := i+1
)
done;
!start, !max_length
;;
(* Exercice 8 *)
let sorteren t =
let zero, one, two = Array.fold_left
(fun (zero, one, two) a -> match a with
| 0 -> zero+1,one,two
| 1 -> zero,one+1,two
| 2 -> zero,one,two+1
| _ -> invalid_arg ""
)
(0,0,0)
t
in
Array.init
(zero+one+two)
(fun i ->
if i < zero then 0
else if i < zero+one then 1
else 2
)
;;
(* Exercice 9 *)
let dominant s =
let counts = Array.make 126 0 in
String.iter (fun c ->
let c = Char.code c in
counts.(c) <- counts.(c) + 1;
) s;
let _, max_c =
Array.fold_left
(fun (c, max_c) a ->
c+1,
if a > counts.(max_c) then c else max_c
)
(0,0)
counts
in
Char.chr max_c
;;