summaryrefslogtreecommitdiffstats
path: root/TestAufgabeFFP4.hs
blob: ff341e5d15a79427f0f6557f96cf4478573d3097 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
module Main where

import Test.HUnit
import Control.Monad
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]

main = do
  forM tests $ \test ->
    runTestTT test