Skip to content

Commit

Permalink
Add Knapsack exercise (#768)
Browse files Browse the repository at this point in the history
* Add Knapsack exercise

* Revert formatting change to track config.json

* Undo accidental indent_size change

* Change indenting to 2 spaces

This is to be consistent with the other exercises that already use 2
spaces.
  • Loading branch information
kahgoh authored Sep 14, 2024
1 parent 07f1f14 commit 8bd0b2f
Show file tree
Hide file tree
Showing 14 changed files with 292 additions and 0 deletions.
8 changes: 8 additions & 0 deletions config.json
Original file line number Diff line number Diff line change
Expand Up @@ -838,6 +838,14 @@
"difficulty": 5,
"topics": ["algorithms", "text_formatting"]
},
{
"slug": "knapsack",
"name": "Knapsack",
"uuid": "1e5a75f5-b269-4297-a6db-d148d81eee5a",
"practices": [],
"prerequisites": [],
"difficulty": 5
},
{
"slug": "linked-list",
"name": "Linked List",
Expand Down
3 changes: 3 additions & 0 deletions exercises/practice/knapsack/.docs/instructions.append.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
## Item representation

The items are represented by the `Item` struct in `Item.swift`.
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.
7 changes: 7 additions & 0 deletions exercises/practice/knapsack/.meta/Sources/Knapsack/Item.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
// Represents an item in knapsack.
// There is be no need to edit this file and changes to this file are ignored by the Exercism test runners.

struct Item {
let weight: Int
let value: Int
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
struct Knapsack {
static func maximumValue(_ items: [Item], _ capacity: Int) -> Int {
if items.count == 0 {
return 0
}

var values: Array<Int> = Array(repeating: 0, count: capacity + 1)
for item in items {
var next: Array<Int> = Array(repeating: 0, count: values.count)
for i in 0..<values.count {
if item.weight <= i {
let valueWith = values[i - item.weight] + item.value
next[i] = max(valueWith, values[i])
} else {
next[i] = values[i]
}
}
values = next
}
return values.last!
}
}
22 changes: 22 additions & 0 deletions exercises/practice/knapsack/.meta/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"authors": [
"kahgoh"
],
"files": {
"solution": [
"Sources/Knapsack/Knapsack.swift"
],
"test": [
"Tests/KnapsackTests/KnapsackTests.swift"
],
"example": [
".meta/Sources/Knapsack/KnapsackExample.swift"
],
"editor": [
"Sources/Knapsack/Item.swift"
]
},
"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"
}
22 changes: 22 additions & 0 deletions exercises/practice/knapsack/.meta/template.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import XCTest
@testable import {{exercise|camelCase}}
class {{exercise|camelCase}}Tests: XCTestCase {
let runAll = Bool(ProcessInfo.processInfo.environment["RUNALL", default: "false"]) ?? false

{% for case in cases %}
{%- if forloop.first %}
func test{{case.description |camelCase}}() {
{%- else %}
func test{{case.description |camelCase}}() throws {
try XCTSkipIf(true && !runAll) // change true to false to run this test
{%- endif %}

let items : [Item] = [
{%- for item in case.input.items %}
{{item | knapsackItem}},
{%- endfor -%}
]
XCTAssertEqual(Knapsack.maximumValue(items, {{case.input.maximumWeight}}), {{case.expected}})
}
{% endfor -%}
}
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"
21 changes: 21 additions & 0 deletions exercises/practice/knapsack/Package.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// swift-tools-version:5.3

import PackageDescription

let package = Package(
name: "Knapsack",
products: [
.library(
name: "Knapsack",
targets: ["Knapsack"])
],
dependencies: [],
targets: [
.target(
name: "Knapsack",
dependencies: []),
.testTarget(
name: "KnapsackTests",
dependencies: ["Knapsack"]),
]
)
7 changes: 7 additions & 0 deletions exercises/practice/knapsack/Sources/Knapsack/Item.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
// Represents an item in knapsack.
// There is be no need to edit this file and changes to this file are ignored by the Exercism test runners.

struct Item {
let weight: Int
let value: Int
}
3 changes: 3 additions & 0 deletions exercises/practice/knapsack/Sources/Knapsack/Knapsack.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
struct Knapsack {
// Write your code for the 'Knapsack' exercise in this file.
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import XCTest

@testable import Knapsack

class KnapsackTests: XCTestCase {
let runAll = Bool(ProcessInfo.processInfo.environment["RUNALL", default: "false"]) ?? false

func testNoItems() {

let items: [Item] = []
XCTAssertEqual(Knapsack.maximumValue(items, 100), 0)
}

func testOneItemTooHeavy() throws {
try XCTSkipIf(true && !runAll) // change true to false to run this test

let items: [Item] = [
Item(weight: 100, value: 1)
]
XCTAssertEqual(Knapsack.maximumValue(items, 10), 0)
}

func testFiveItemsCannotBeGreedyByWeight() throws {
try XCTSkipIf(true && !runAll) // change true to false to run this test

let items: [Item] = [
Item(weight: 2, value: 5),
Item(weight: 2, value: 5),
Item(weight: 2, value: 5),
Item(weight: 2, value: 5),
Item(weight: 10, value: 21),
]
XCTAssertEqual(Knapsack.maximumValue(items, 10), 21)
}

func testFiveItemsCannotBeGreedyByValue() throws {
try XCTSkipIf(true && !runAll) // change true to false to run this test

let items: [Item] = [
Item(weight: 2, value: 20),
Item(weight: 2, value: 20),
Item(weight: 2, value: 20),
Item(weight: 2, value: 20),
Item(weight: 10, value: 50),
]
XCTAssertEqual(Knapsack.maximumValue(items, 10), 80)
}

func testExampleKnapsack() throws {
try XCTSkipIf(true && !runAll) // change true to false to run this test

let items: [Item] = [
Item(weight: 5, value: 10),
Item(weight: 4, value: 40),
Item(weight: 6, value: 30),
Item(weight: 4, value: 50),
]
XCTAssertEqual(Knapsack.maximumValue(items, 10), 90)
}

func test8Items() throws {
try XCTSkipIf(true && !runAll) // change true to false to run this test

let items: [Item] = [
Item(weight: 25, value: 350),
Item(weight: 35, value: 400),
Item(weight: 45, value: 450),
Item(weight: 5, value: 20),
Item(weight: 25, value: 70),
Item(weight: 3, value: 8),
Item(weight: 2, value: 5),
Item(weight: 2, value: 5),
]
XCTAssertEqual(Knapsack.maximumValue(items, 104), 900)
}

func test15Items() throws {
try XCTSkipIf(true && !runAll) // change true to false to run this test

let items: [Item] = [
Item(weight: 70, value: 135),
Item(weight: 73, value: 139),
Item(weight: 77, value: 149),
Item(weight: 80, value: 150),
Item(weight: 82, value: 156),
Item(weight: 87, value: 163),
Item(weight: 90, value: 173),
Item(weight: 94, value: 184),
Item(weight: 98, value: 192),
Item(weight: 106, value: 201),
Item(weight: 110, value: 210),
Item(weight: 113, value: 214),
Item(weight: 115, value: 221),
Item(weight: 118, value: 229),
Item(weight: 120, value: 240),
]
XCTAssertEqual(Knapsack.maximumValue(items, 750), 1458)
}
}
9 changes: 9 additions & 0 deletions generator/Sources/Generator/generator-plugins.swift
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,15 @@ class GeneratorPlugins {
return nil
}

ext.registerFilter("knapsackItem") { (value: Any?) in
if let item = value as? [String: Any] {
let itemWeight = String(describing: item["weight", default: ""])
let itemValue = String(describing: item["value", default: ""])
return "Item(weight:\(itemWeight), value:\(itemValue))"
}
return "// Something else ..."
}

let environment = Environment(extensions: [ext])
return environment
}
Expand Down

0 comments on commit 8bd0b2f

Please sign in to comment.