Skip to content

Commit

Permalink
Add Knapsack exercise (#116)
Browse files Browse the repository at this point in the history
  • Loading branch information
kahgoh authored Jul 3, 2024
1 parent 01a866e commit 649dea2
Show file tree
Hide file tree
Showing 15 changed files with 10,196 additions and 0 deletions.
8 changes: 8 additions & 0 deletions config.json
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,14 @@
"practices": [],
"prerequisites": [],
"difficulty": 6
},
{
"slug": "knapsack",
"name": "Knapsack",
"uuid": "ab83ccd8-1b28-41ab-b24a-d1da9297ce28",
"practices": [],
"prerequisites": [],
"difficulty": 8
}
]
},
Expand Down
18 changes: 18 additions & 0 deletions exercises/practice/knapsack/.docs/instructions.append.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Instructions append

## WebAssembly-specific Notes

The items are passed through linear memory, with the first item at offset 0.
Each item is represented as a pair of 32-bit integers.
The first number in the pair is the weight and the second is the value.

For example, consider a list of two items, where the first has `weight=1, value=2` and the second `weight=5, value=8`.
The list would thus look like this in memory:

```
| 00 | 01 | 02 | 03 | 04 | 05 | 06 | 07 | 08 | 09 | 10 | 11 | 12 | 13 | 14 | 15 |
| - item 1 weight - | -- item 1 value - | - item 2 weight - | -- item 2 value - |
|0x01,0x00,0x00,0x00|0x02,0x00,0x00,0x00|0x05,0x00,0x00,0x00|0x08,0x00,0x00,0x00|
```

If you so choose, you may overwrite the addresses of linear memory used for the input.
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.
14 changes: 14 additions & 0 deletions exercises/practice/knapsack/.eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"root": true,
"extends": "@exercism/eslint-config-javascript",
"env": {
"jest": true
},
"overrides": [
{
"files": ["*.spec.js"],
"excludedFiles": ["custom.spec.js"],
"extends": "@exercism/eslint-config-javascript/maintainers"
}
]
}
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": [
"knapsack.wat"
],
"test": [
"knapsack.spec.js"
],
"example": [
".meta/proof.ci.wat"
]
},
"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"
}
93 changes: 93 additions & 0 deletions exercises/practice/knapsack/.meta/proof.ci.wat
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
(module
(memory (export "mem") 1)

(func $maximumValue (param $itemsOffset i32) (param $itemsCount i32) (param $capacity i32) (result i32)
(local $itemWeight i32)
(local $itemValue i32)
(local $valueWith i32)
(local $valueWithout i32)

(if
(i32.eq
(local.get $itemsCount)
(i32.const 0))
(then (return (i32.const 0)))
)

(local.set $itemWeight (i32.load (local.get $itemsOffset)))

(local.set $valueWithout
(call
$maximumValue
(i32.add
(local.get $itemsOffset)
(i32.const 8)
)
(i32.sub
(local.get $itemsCount)
(i32.const 1)
)
(local.get $capacity)
)
)

(if
(i32.lt_u
(local.get $capacity)
(local.get $itemWeight)
)
(then
(return
(local.get $valueWithout)
)
)
)

(local.set $itemValue
(i32.load
(i32.add
(local.get $itemsOffset)
(i32.const 4)
)
)
)
(local.set $valueWith
(i32.add
(local.get $itemValue)
(call
$maximumValue
(i32.add
(local.get $itemsOffset)
(i32.const 8))
(i32.sub
(local.get $itemsCount)
(i32.const 1))
(i32.sub
(local.get $capacity)
(local.get $itemWeight))
)
)
)

(if
(i32.gt_u
(local.get $valueWith)
(local.get $valueWithout))
(then
(return (local.get $valueWith))
)
)

(return (local.get $valueWithout))
)

;; Determine the maximum total value that can be carried
;;
;; @param {i32} itemsCount - The number of items
;; @param {i32} capacity - How much weight the knapsack can carry
;; @returns {i32} the maximum value
;;
(func (export "maximumValue") (param $itemsCount i32) (param $capacity i32) (result i32)
(return (call $maximumValue (i32.const 0) (local.get $itemsCount) (local.get $capacity)))
)
)
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"
1 change: 1 addition & 0 deletions exercises/practice/knapsack/.npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
audit=false
21 changes: 21 additions & 0 deletions exercises/practice/knapsack/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2021 Exercism

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
4 changes: 4 additions & 0 deletions exercises/practice/knapsack/babel.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export default {
presets: ["@exercism/babel-preset-javascript"],
plugins: [],
};
117 changes: 117 additions & 0 deletions exercises/practice/knapsack/knapsack.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
import { compileWat, WasmRunner } from "@exercism/wasm-lib";

let wasmModule;
let currentInstance;

beforeAll(async () => {
try {
const watPath = new URL("./knapsack.wat", import.meta.url);
const { buffer } = await compileWat(watPath);
wasmModule = await WebAssembly.compile(buffer);
} catch (err) {
console.log(`Error compiling *.wat: \n${err}`);
process.exit(1);
}
});

function findMaximumValue(items, capacity) {
let data = currentInstance.get_mem_as_i32(0, items.length * 2);
for (let i in items) {
const index = i * 2;
data[index] = items[i]["weight"];
data[index + 1] = items[i]["value"];
}
return currentInstance.exports.maximumValue(items.length, capacity);
}

describe("knapsack", () => {
beforeEach(async () => {
currentInstance = null;
if (!wasmModule) {
return Promise.reject();
}
try {
currentInstance = await new WasmRunner(wasmModule);
return Promise.resolve();
} catch (err) {
console.log(`Error instantiating WebAssembly module: ${err}`);
return Promise.reject();
}
});

test("no items", () => {
expect(findMaximumValue([], 100)).toEqual(0);
});

xtest("one item, too heavy", () => {
const items = [{ "weight": 100, "value": 1 }];
expect(findMaximumValue(items, 10)).toEqual(0);
});

xtest("five items (cannot be greedy by weight)", () => {
const items = [
{ "weight": 2, "value": 5 },
{ "weight": 2, "value": 5 },
{ "weight": 2, "value": 5 },
{ "weight": 2, "value": 5 },
{ "weight": 10, "value": 21 }
];
expect(findMaximumValue(items, 10)).toEqual(21);
});

xtest("five items (cannot be greedy by value)", () => {
const items = [
{ "weight": 2, "value": 20 },
{ "weight": 2, "value": 20 },
{ "weight": 2, "value": 20 },
{ "weight": 2, "value": 20 },
{ "weight": 10, "value": 50 }
];
expect(findMaximumValue(items, 10)).toEqual(80);
});

xtest("example knapsack", () => {
const items = [
{ "weight": 5, "value": 10 },
{ "weight": 4, "value": 40 },
{ "weight": 6, "value": 30 },
{ "weight": 4, "value": 50 }
];
expect(findMaximumValue(items, 10)).toEqual(90);
});

xtest("8 items", () => {
const items = [
{ "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 }
];
expect(findMaximumValue(items, 104)).toEqual(900);
});

xtest("15 items", () => {
const items = [
{ "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 }
];
expect(findMaximumValue(items, 750)).toEqual(1458);
});
});
14 changes: 14 additions & 0 deletions exercises/practice/knapsack/knapsack.wat
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
(module
(memory (export "mem") 1)

;; Determine the maximum total value that can be carried
;;
;; @param {i32} itemsCount - The number of items
;; @param {i32} capacity - How much weight the knapsack can carry
;; @returns {i32} the maximum value
;;
(func (export "maximumValue") (param $itemsCount i32) (param $capacity i32) (result i32)
;; Please implement the maximumValue function.
(return (i32.const 0))
)
)
Loading

0 comments on commit 649dea2

Please sign in to comment.