Skip to content
This repository has been archived by the owner on Jul 10, 2024. It is now read-only.

Commit

Permalink
Smallest 3 elements in Haskell (#5725)
Browse files Browse the repository at this point in the history
Co-authored-by: Riyazul555 <riyazulislam2003@gmail.com>
Co-authored-by: Ritesh Kokam <61982298+RiteshK-611@users.noreply.github.com>
  • Loading branch information
3 people committed Jun 19, 2024
1 parent 6eb5f85 commit 8e808a4
Showing 1 changed file with 22 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit 8e808a4

Please sign in to comment.