#!/usr/bin/runhugs +l module Main where import Test.HUnit import Control.Monad import System import Data.Array import AufgabeFFP4 ------------------------------------------------------------------------------- import Data.List type KnapsackWantedSolution = (SolKnp,Value) type KnapsackWantedSolutions = [KnapsackWantedSolution] type KnapsackGotSolution = (SolKnp,Value) knapsackOk :: KnapsackWantedSolutions -> KnapsackGotSolution -> Bool knapsackOk wanted got = any (equalKnapsack got) wanted where equalKnapsack (sg,vg) (sw,vw) = vg == vw && equalKnapsackContent sg sw equalKnapsackContent sg sw = sort sg == sort sw assertKnapsackOneOf :: String -> KnapsackWantedSolutions -> KnapsackGotSolution -> Assertion assertKnapsackOneOf preface expected actual = unless (knapsackOk expected actual) (assertFailure msg) where msg = (if null preface then "" else preface ++ "\n") ++ "expected one of: " ++ show expected ++ "\n but got: " ++ show actual ------------------------------------------------------------------------------- cases1 = TestLabel "knapsack" $ TestList [ TestCase $ assertKnapsackOneOf "exercise example" [([(2,3), (2,3), (3,4), (3,4)], 14)] (knapsack [(2,3), (2,3), (3,4), (3,4), (5,6)] 10), TestCase $ assertKnapsackOneOf "no objects" [([], 0)] (knapsack [(2,3), (2,3), (3,4), (3,4), (5,6)] 1), TestCase $ assertKnapsackOneOf "all objects" [([(2,3), (2,3), (3,4), (3,4), (5,6)], 20)] (knapsack [(2,3), (2,3), (3,4), (3,4), (5,6)] 100), TestCase $ assertKnapsackOneOf "a" [([(2,2), (3,3)], 5), ([(5,5)], 5)] (knapsack [(2,2), (3,3), (4,4), (5,5)] 5) ] -- from Aufgabe3.hs binom :: (Integer, Integer) -> Integer binom (n, k) | k == 0 || n == k = 1 | otherwise = binom (n-1, k-1) + binom (n-1, k) cases2 = TestLabel "binomDyn" $ TestList [ TestCase $ assertEqual "8 nCr [0..7]" [ binom (8, i) | i <- [0..7] ] [ binomDyn (8, i) | i <- [0..7] ], TestCase $ assertEqual "1 nCr 1" (binom (1, 1)) (binomDyn (1, 1)), TestCase $ assertEqual "2 nCr 1" (binom (2, 1)) (binomDyn (2, 1)), TestCase $ assertEqual "18 nCr 12" (binom (18, 12)) (binomDyn (18, 12)), TestCase $ assertEqual "5 nCr 0" (binom (5, 0)) (binomDyn (5, 0)) ] tests :: [Test] tests = [cases1, cases2] isSuccess :: Counts -> Bool isSuccess Counts{ cases = _, tried = _, errors = 0, failures = 0 } = True isSuccess Counts{ cases = _, tried = _, errors = _, failures = _ } = False runTest :: Test -> IO () runTest test = do result <- runTestTT test unless (isSuccess result) exitFailure main = do forM tests $ (\test -> runTest test)