From 8e808a42029bc788ba1d6b3b1f1f238a734dbb8c Mon Sep 17 00:00:00 2001 From: Md Riyazul Islam <121575277+Riyazul555@users.noreply.github.com> Date: Wed, 19 Jun 2024 23:20:59 +0530 Subject: [PATCH] Smallest 3 elements in Haskell (#5725) Co-authored-by: Riyazul555 Co-authored-by: Ritesh Kokam <61982298+RiteshK-611@users.noreply.github.com> --- ...the_smallest_three_elements_in_an_array.hs | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 program/program/find-the-smallest-three-elements-in-an-array/find_the_smallest_three_elements_in_an_array.hs diff --git a/program/program/find-the-smallest-three-elements-in-an-array/find_the_smallest_three_elements_in_an_array.hs b/program/program/find-the-smallest-three-elements-in-an-array/find_the_smallest_three_elements_in_an_array.hs new file mode 100644 index 000000000..33741933a --- /dev/null +++ b/program/program/find-the-smallest-three-elements-in-an-array/find_the_smallest_three_elements_in_an_array.hs @@ -0,0 +1,22 @@ +import Data.List (foldl') + +-- Function to find the smallest three elements +findSmallestThree :: [Int] -> [Int] +findSmallestThree arr + | length arr < 3 = error "Array should have at least 3 elements" + | otherwise = let (a, b, c) = foldl' update (maxBound, maxBound, maxBound) arr + in [a, b, c] + where + update :: (Int, Int, Int) -> Int -> (Int, Int, Int) + update (first, second, third) x + | x < first = (x, first, second) + | x < second = (first, x, second) + | x < third = (first, second, x) + | otherwise = (first, second, third) + +-- Example usage +main :: IO () +main = do + let arr = [12, 13, 1, 10, 34, 1] + let smallestThree = findSmallestThree arr + putStrLn $ "The smallest three elements are: " ++ show smallestThree