Skip to content

Commit

Permalink
Add Knapsack exercise (#304)
Browse files Browse the repository at this point in the history
  • Loading branch information
kahgoh authored Jul 21, 2024
1 parent 47004bb commit 19879b0
Show file tree
Hide file tree
Showing 11 changed files with 274 additions and 0 deletions.
8 changes: 8 additions & 0 deletions config.json
Original file line number Diff line number Diff line change
Expand Up @@ -404,6 +404,14 @@
"practices": [],
"prerequisites": [],
"difficulty": 5
},
{
"slug": "knapsack",
"name": "Knapsack",
"uuid": "7a970ee7-7ef9-442b-92d5-4784e7c6fcd1",
"practices": [],
"prerequisites": [],
"difficulty": 5
}
]
},
Expand Down
25 changes: 25 additions & 0 deletions exercises/practice/knapsack/.docs/instructions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Instructions

Your task is to determine which items to take so that the total value of his selection is maximized, taking into account the knapsack's carrying capacity.

Items will be represented as a list of items.
Each item will have a weight and value.
All values given will be strictly positive.
Bob can take only one of each item.

For example:

```text
Items: [
{ "weight": 5, "value": 10 },
{ "weight": 4, "value": 40 },
{ "weight": 6, "value": 30 },
{ "weight": 4, "value": 50 }
]
Knapsack Maximum Weight: 10
```

For the above, the first item has weight 5 and value 10, the second item has weight 4 and value 40, and so on.
In this example, Bob should take the second and fourth item to maximize his value, which, in this case, is 90.
He cannot get more than 90 as his knapsack has a weight limit of 10.
8 changes: 8 additions & 0 deletions exercises/practice/knapsack/.docs/introduction.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# Introduction

Bob is a thief.
After months of careful planning, he finally manages to crack the security systems of a fancy store.

In front of him are many items, each with a value and weight.
Bob would gladly take all of the items, but his knapsack can only hold so much weight.
Bob has to carefully consider which items to take so that the total value of his selection is maximized.
19 changes: 19 additions & 0 deletions exercises/practice/knapsack/.meta/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"authors": [
"kahgoh"
],
"files": {
"solution": [
"src/Knapsack.purs"
],
"test": [
"test/Main.purs"
],
"example": [
"examples/src/Knapsack.purs"
]
},
"blurb": "Given a knapsack that can only carry a certain weight, determine which items to put in the knapsack in order to maximize their combined value.",
"source": "Wikipedia",
"source_url": "https://en.wikipedia.org/wiki/Knapsack_problem"
}
36 changes: 36 additions & 0 deletions exercises/practice/knapsack/.meta/tests.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# This is an auto-generated file.
#
# Regenerating this file via `configlet sync` will:
# - Recreate every `description` key/value pair
# - Recreate every `reimplements` key/value pair, where they exist in problem-specifications
# - Remove any `include = true` key/value pair (an omitted `include` key implies inclusion)
# - Preserve any other key/value pair
#
# As user-added comments (using the # character) will be removed when this file
# is regenerated, comments can be added via a `comment` key.

[a4d7d2f0-ad8a-460c-86f3-88ba709d41a7]
description = "no items"
include = false

[3993a824-c20e-493d-b3c9-ee8a7753ee59]
description = "no items"
reimplements = "a4d7d2f0-ad8a-460c-86f3-88ba709d41a7"

[1d39e98c-6249-4a8b-912f-87cb12e506b0]
description = "one item, too heavy"

[833ea310-6323-44f2-9d27-a278740ffbd8]
description = "five items (cannot be greedy by weight)"

[277cdc52-f835-4c7d-872b-bff17bab2456]
description = "five items (cannot be greedy by value)"

[81d8e679-442b-4f7a-8a59-7278083916c9]
description = "example knapsack"

[f23a2449-d67c-4c26-bf3e-cde020f27ecc]
description = "8 items"

[7c682ae9-c385-4241-a197-d2fa02c81a11]
description = "15 items"
5 changes: 5 additions & 0 deletions exercises/practice/knapsack/.solution.dhall
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
let conf = ./spago.dhall

in conf // {
sources = [ "examples/src/*.purs", "test/**/*.purs" ],
}
53 changes: 53 additions & 0 deletions exercises/practice/knapsack/examples/src/Knapsack.purs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
module Knapsack
(maximumValue
, Item
) where

import Prelude
import Data.Array as Array
import Data.Array(replicate)
import Data.Maybe (Maybe(..))
import Effect.Exception.Unsafe (unsafeThrow)

type Item =
{ value :: Int
, weight :: Int
}

orThrow :: Maybe Int -> Int
orThrow v = case v of
Nothing -> unsafeThrow "no value"
(Just v) -> v

findMaxValue :: Item -> Int -> Array Int -> Int
findMaxValue { value: v, weight: w} cap prevRow
| w > cap = orThrow $ Array.index prevRow cap
| otherwise = let
valueWithout = orThrow $ Array.index prevRow cap
valueWith = v + (orThrow $ Array.index prevRow (cap - w))
in
if valueWith > valueWithout then
valueWith
else
valueWithout

findMaxValues :: Array Item -> Int -> Array Int -> Int
findMaxValues items index prevRow
| (Array.length items) <= index = orThrow $ Array.last prevRow
| otherwise = let
item = case Array.index items index of
Nothing -> unsafeThrow "no item"
(Just i) -> i
in
let
nextRow = Array.mapWithIndex (\i _v -> findMaxValue item i prevRow) prevRow
in
findMaxValues items (index + 1) nextRow

maximumValue :: Array Item -> Int -> Int
maximumValue [] _capacity = 0
maximumValue items capacity =
let
initial = replicate (capacity + 1) 0
in
findMaxValues items 0 initial
5 changes: 5 additions & 0 deletions exercises/practice/knapsack/packages.dhall
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
let upstream =
https://github.com/purescript/package-sets/releases/download/psc-0.14.7-20220418/packages.dhall
sha256:2523a5659d0f3b198ffa2f800da147e0120578842e492a7148e4b44f357848b3

in upstream
27 changes: 27 additions & 0 deletions exercises/practice/knapsack/spago.dhall
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{ name = "knapsack"
, dependencies =
[ "arrays"
, "console"
, "datetime"
, "effect"
, "either"
, "enums"
, "exceptions"
, "foldable-traversable"
, "integers"
, "lists"
, "math"
, "maybe"
, "ordered-collections"
, "partial"
, "prelude"
, "psci-support"
, "strings"
, "test-unit"
, "tuples"
, "unfoldable"
, "unicode"
]
, packages = ./packages.dhall
, sources = [ "src/**/*.purs", "test/**/*.purs" ]
}
15 changes: 15 additions & 0 deletions exercises/practice/knapsack/src/Knapsack.purs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
module Knapsack
(maximumValue
, Item
) where

import Prelude
import Effect.Exception.Unsafe (unsafeThrow)

type Item =
{ value :: Int
, weight :: Int
}

maximumValue :: Array Item -> Int -> Int
maximumValue _items _capacity = unsafeThrow "You need to implement this function."
73 changes: 73 additions & 0 deletions exercises/practice/knapsack/test/Main.purs
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
module Test.Main where

import Prelude

import Effect (Effect)
import Test.Unit (TestSuite, suite, test)
import Test.Unit.Main (runTest)
import Test.Unit.Assert as Assert
import Knapsack as Knapsack

main :: Effect Unit
main = runTest suites


suites :: TestSuite
suites = do
suite "Knapsack.maximumValue" do
test "no items" do
Assert.equal 0 $ Knapsack.maximumValue [] 100
test "one item, too heavy" do
Assert.equal 0 $ Knapsack.maximumValue [{weight: 100, value: 1}] 0
test "five items (cannot be greedy by weight)" do
Assert.equal 21 $ Knapsack.maximumValue [{weight: 2, value: 5}
,{weight: 2, value: 5}
,{weight: 2, value: 5}
,{weight: 2, value: 5}
,{weight: 10, value: 21}
]
10
test "five items (cannot be greedy by value)" do
Assert.equal 80 $ Knapsack.maximumValue [{weight: 2, value: 20}
,{weight: 2, value: 20}
,{weight: 2, value: 20}
,{weight: 2, value: 20}
,{weight: 10, value: 50}
]
10
test "example knapsack" do
Assert.equal 90 $ Knapsack.maximumValue [{weight: 5, value: 10}
,{weight: 4, value: 40}
,{weight: 6, value: 30}
,{weight: 4, value: 50}
]
10
test "8 items" do
Assert.equal 900 $ Knapsack.maximumValue [{weight: 25, value: 350}
,{weight: 35, value: 400}
,{weight: 45, value: 450}
,{weight: 5, value: 20}
,{weight: 25, value: 70}
,{weight: 3, value: 8}
,{weight: 2, value: 5}
,{weight: 2, value: 5}
]
104
test "15 items" do
Assert.equal 1458 $ Knapsack.maximumValue [{weight: 70, value: 135}
,{weight: 73, value: 139}
,{weight: 77, value: 149}
,{weight: 80, value: 150}
,{weight: 82, value: 156}
,{weight: 87, value: 163}
,{weight: 90, value: 173}
,{weight: 94, value: 184}
,{weight: 98, value: 192}
,{weight: 106, value: 201}
,{weight: 110, value: 210}
,{weight: 113, value: 214}
,{weight: 115, value: 221}
,{weight: 118, value: 229}
,{weight: 120, value: 240}
]
750

0 comments on commit 19879b0

Please sign in to comment.