module Exercise02 where import Data.List import Data.Ord {-H2.1a)-} twoThirdsAverageWinners :: [(String, Int)] -> [String] twoThirdsAverageWinners gs = [n | (n, d) <- dists, d == mindist] where s = sum $ map snd gs l = fromIntegral $ length gs dists = [(n, abs (b - s * 2 `div` (l * 3))) | (n, b) <- gs] mindist = minimum $ map snd dists {-H2.1b)-} lowestUniqueBidder :: [(String, Int)] -> String lowestUniqueBidder bs = takeFirstUnique $ sortOn snd bs where takeFirstUnique [] = "Nobody" takeFirstUnique [x] = fst x takeFirstUnique ((xn, xb) : (_, yb) : _) | xb /= yb = xn takeFirstUnique [_, _] = takeFirstUnique [] takeFirstUnique (_ : (yn, yb) : (zn, zb) : rs) | yb /= zb = takeFirstUnique ((zn, zb) : rs) | otherwise = takeFirstUnique ((yn, yb) : (zn, zb) : rs) {-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 = [j | j <- players tournament, i `elem` dominion tournament j] {-H2.2b)-} covers :: [[Int]] -> Int -> Int -> Bool covers tournament i j = and [k `elem` dominion tournament i | k <- dominion tournament j] {-2.2c)-} dominant :: [[Int]] -> [Int] -> Bool dominant _ [] = False dominant tournament xs = and [isSubsequenceOf ys $ dominion tournament x | x <- xs] where ys = [p | p <- players tournament, p `notElem` xs] {-WETT-} {-H2.2d)-} copeland :: [[Int]] -> [Int] copeland tournament = [i | i <- players tournament, length (dominion tournament i) == maximum [length $ dominion tournament j | j <- players tournament]] {-H2.2e)-} uncoveredSet :: [[Int]] -> [Int] uncoveredSet tournament = [i | i <- players tournament, null [j | j <- players tournament, j /= i, covers tournament j i]] {-H2.2f)-} topCycle :: [[Int]] -> [Int] topCycle tournament = withAllDominators (uncoveredSet tournament) $ length $ players tournament where withAllDominators xs 0 = xs withAllDominators xs n = withAllDominators (nub $ concatMap (dominators tournament) xs ++ xs) $ n-1 {-TTEW-}