From 0b9230c8cb8f4d43e6c434b4af243b3385346b65 Mon Sep 17 00:00:00 2001 From: Louis Date: Fri, 6 Oct 2023 14:15:02 +0200 Subject: [PATCH] vault backup: 2023-10-06 14:15:02 --- Algo/Courses/Chapter 6 - Lists (Exercises).md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/Algo/Courses/Chapter 6 - Lists (Exercises).md b/Algo/Courses/Chapter 6 - Lists (Exercises).md index 9de6d72..0572dec 100644 --- a/Algo/Courses/Chapter 6 - Lists (Exercises).md +++ b/Algo/Courses/Chapter 6 - Lists (Exercises).md @@ -64,3 +64,22 @@ let rec max_value list = match list with ## 1.6 - Bonus second ```Ocaml +let rec second_smallest list = + match list with + | [] | [_] -> failwith "La liste ne contient pas au moins deux éléments distincts" + | [x; y] -> if x < y then y else x + | hd1 :: hd2 :: tl -> + let min1, min2 = + if hd1 < hd2 then (hd1, hd2) else (hd2, hd1) + in + let rec find_second_smallest rest = + match rest with + | [] -> min2 + | hd :: tl -> + if hd < min1 then find_second_smallest (min1 :: tl) + else if hd < min2 && hd > min1 then find_second_smallest (hd :: min1 :: tl) + else find_second_smallest (min2 :: tl) + in + find_second_smallest tl +``` +