Skip to content

Commit 9af6336

Browse files
committed
Solve 'Simple Fun #5: Knapsack Light' kata
1 parent fc08dfd commit 9af6336

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

src/Knapsack.hs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
module Knapsack (knapsackLight) where
2+
3+
-- https://www.codewars.com/kata/58842a2b4e8efb92b7000080/train/haskell
4+
5+
knapsackLight :: Int -> Int -> Int -> Int -> Int -> Int
6+
knapsackLight value1 weight1 value2 weight2 maxW
7+
| weight1 > maxW && weight2 > maxW = 0
8+
| weight1 > maxW = value2
9+
| weight2 > maxW = value1
10+
| weight1 + weight2 > maxW = max value1 value2
11+
| otherwise = value1 + value2

test/KnapsackSpec.hs

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
module KnapsackSpec where
2+
3+
import Knapsack (knapsackLight)
4+
import Test.HUnit
5+
import Test.Hspec
6+
import Text.Printf
7+
8+
spec :: Spec
9+
spec = do
10+
describe "Fixed Tests" $ do
11+
it "Basic Cases" $ do
12+
fixedTest (10, 5, 6, 4, 8) 10
13+
fixedTest (10, 5, 6, 4, 9) 16
14+
fixedTest (10, 10, 6, 10, 9) 0
15+
fixedTest (10, 2, 11, 3, 1) 0
16+
fixedTest (15, 2, 20, 3, 2) 15
17+
fixedTest (2, 5, 3, 4, 5) 3
18+
fixedTest (4, 3, 3, 4, 4) 4
19+
fixedTest (3, 5, 3, 8, 10) 3
20+
where
21+
fixedTest inp@(v1, w1, v2, w2, mw) exp =
22+
assertEqual (showInput inp) exp $
23+
knapsackLight v1 w1 v2 w2 mw
24+
25+
showInput :: (Int, Int, Int, Int, Int) -> String
26+
showInput (a, b, c, d, e) = printf "knapsackLight %d %d %d %d %d" a b c d e

0 commit comments

Comments
 (0)