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

Commit

Permalink
Write a Haskell program to find the largest three elements in an array
Browse files Browse the repository at this point in the history
#5173  (#5606)

* Solves issue with swift not finding the largest two elements correctly

* Solves  #5560 Write a Scala program to convert temperature from celsius to kelvin

* Removes #5560 changes

* F# program to implement linear search (#5295)

* Solves 5173: Write a Haskell program to find the largest three elements in an array

---------

Co-authored-by: David Fernandez <david@Davids-MacBook-Pro.local>
Co-authored-by: Harsh Raj <harshraj8843@gmail.com>
Co-authored-by: Anandha Krishnan S <anandajith@gmail.com>
  • Loading branch information
4 people authored Apr 4, 2024
1 parent a04320b commit 69f05e5
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import Data.List (delete)

findLargestThree :: Ord a => [a] -> [a]
findLargestThree arr = take 3 (largestThree arr)

largestThree :: Ord a => [a] -> [a]
largestThree [] = []
largestThree [x] = [x]
largestThree [x, y] = [max x y]
largestThree (x:y:z:xs) = let largest = maximumOfThree x y z
in largest : largestThree (delete largest (x:y:z:xs))

maximumOfThree :: Ord a => a -> a -> a -> a
maximumOfThree x y z = max x (max y z)

main :: IO ()
main = do
let arr1 = [10, 4, 3, 50, 23, 90]
let arr2 = [10, 4, 3, 50, 23, 90, 1, 100, 49]
putStrLn "Input array 1: "
print arr1
putStrLn "Largest three elements: "
print (findLargestThree arr1)
putStrLn "Input array 2: "
print arr2
putStrLn "Largest three elements: "
print (findLargestThree arr2)

Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
func findLargestTwo(_ arr: [Int]) -> (Int, Int) {
var firstLargest = Int.min
var secondLargest = Int.min

for num in arr {
if num > firstLargest {
secondLargest = firstLargest
firstLargest = num
} else if num > secondLargest && num != firstLargest {
secondLargest = num
}
}

return (firstLargest, secondLargest)
}

// Test cases
let arr1 = [12, 13, 1, 10, 34, 1]
let arr2 = [10, 5, 10]
let arr3 = [10, 10, 10]

let result1 = findLargestTwo(arr1)
let result2 = findLargestTwo(arr2)
let result3 = findLargestTwo(arr3)

print("The largest two elements are \(result1.0) and \(result1.1)")
print("The largest two elements are \(result2.0) and \(result2.1)")
print("The largest two elements are \(result3.0) and \(result3.1)")

0 comments on commit 69f05e5

Please sign in to comment.