module Exercise02 where import Data.List import Data.Ord {-H2.1a)-} twoThirdsAverageWinners :: [(String, Int)] -> [String] twoThirdsAverageWinners gs = [fst x | x <- gs, cmp2 (foldl1 cmp gs) x] where avg = div (2 * sum [snd x | x <- gs]) (3 * length gs) cmp x y = if abs (snd x - avg) <= abs (snd y - avg) then x else y cmp2 x y = abs (snd x - avg) == abs (snd y - avg) {-H2.1b)-} lowestUniqueBidder :: [(String, Int)] -> String lowestUniqueBidder bs | null bs = "Nobody" | length bs == 1 = fst (head bs) | otherwise = if length bsSorted - 1 == length bsFiltered then fst (head bsSorted) else lowestUniqueBidder bsFiltered where bsSorted = sortOn snd bs bsFiltered = filter cmp (tail bsSorted) cmp x = snd x /= snd (head bsSorted) {-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 = [snd y | y <- filter fst (zip [i `elem` x | x <- tournament] (players tournament))] {-H2.2b)-} covers :: [[Int]] -> Int -> Int -> Bool covers tournament i j = all not [x `notElem` domI | x <- dominion tournament j] where domI = dominion tournament i {-2.2c)-} dominant :: [[Int]] -> [Int] -> Bool dominant tournament xs | null xs = False | otherwise = all not [y `notElem` dominion tournament x | x <- xs, y <- [x | x <- players tournament, x `notElem` xs]] {-WETT-} {-H2.2d)-} copeland :: [[Int]] -> [Int] copeland tournament = map (+ 1) $maximum x `elemIndices` x where x = map length tournament {-H2.2e)-} uncoveredSet :: [[Int]] -> [Int] uncoveredSet tournament = players tournament \\ [y | x <- players tournament, y <- players tournament, covers tournament x y, x /= y] {-H2.2f)-} topCycle :: [[Int]] -> [Int] topCycle tournament = (\xs -> nub $concatMap (tournament `dominators`) xs ++ xs) `iterate` copeland tournament !! length tournament {-TTEW-}