module Exercise02 where import Data.List import Data.Ord {-H2.1a)-} twoThirdsAverageWinners :: [(String, Int)] -> [String] twoThirdsAverageWinners gs = filt gs where filt [] = [] filt (x : xs) = if snd x `elem` filteredInts then fst x : filt xs else filt xs filteredInts = map fst (filter ((== minDifference) . snd) diffList) minDifference = snd (minimumBy (comparing snd) diffList) diffList = zip (map snd gs) (map (abs . subtract averageDivided . snd) gs) averageDivided = (2 * sum (map snd gs) `div` length gs) `div` 3 {-H2.1b)-} lowestUniqueBidder :: [(String, Int)] -> String lowestUniqueBidder bs = if null (filt sorted) then "Nobody" else fst (head (filter ((== head (filt sorted)) . snd) bs)) where sorted = sort (map snd bs) filt [] = [] filt (x : xs) = if x `elem` xs then filt (filter (/= x) xs) else x : filt xs {-H2-} -- returns the shortest list in a list of lists shortest :: [[Int]] -> [Int] shortest = minimumBy (comparing length) -- returns the set of all players in a tournament players :: [[Int]] -> [Int] players tournament = [1 .. length tournament] -- returns the dominion of player i dominion :: [[Int]] -> Int -> [Int] dominion tournament i = tournament !! (i - 1) {-H2.2a)-} dominators :: [[Int]] -> Int -> [Int] dominators tournament i = iterate 1 tournament where iterate _ [] = [] iterate j (x : xs) = if i `elem` x then j : iterate (j + 1) xs else iterate (j + 1) xs {-H2.2b)-} covers :: [[Int]] -> Int -> Int -> Bool covers tournament i j = all (`elem` dominion tournament i) (dominion tournament j) {-2.2c)-} dominant :: [[Int]] -> [Int] -> Bool dominant tournament xs = not (null xs) && all (\x -> complement == intersect complement (dominion tournament x)) xs where complement = players tournament \\ xs {-WETT-} {-H2.2d)-} copeland :: [[Int]] -> [Int] copeland tournament = filter ((== maximum (map length tournament)) . length . dominion tournament) $ players tournament {-H2.2e)-} uncoveredSet :: [[Int]] -> [Int] uncoveredSet tournament = players tournament \\ [x | x <- players tournament, y <- delete x $players tournament, covers tournament y x] {-H2.2f)-} topCycle :: [[Int]] -> [Int] topCycle tournament = head $ filter (dominant tournament) $ inits $ sortOn (length . dominators tournament) $players tournament {-TTEW-}