From c7e2c71bae5ebf2953dd517d3c029cdd9fb8b391 Mon Sep 17 00:00:00 2001 From: Jesse Kroon Date: Thu, 1 Feb 2024 09:31:35 +0100 Subject: [PATCH] create working example and fleshing out the Knapsack function --- exercises/practice/knapsack/.meta/example.go | 28 ++++++++++++++++++++ exercises/practice/knapsack/knapsack.go | 4 ++- exercises/practice/knapsack/knapsack_test.go | 2 +- 3 files changed, 32 insertions(+), 2 deletions(-) diff --git a/exercises/practice/knapsack/.meta/example.go b/exercises/practice/knapsack/.meta/example.go index e69de29bb..35db4824f 100644 --- a/exercises/practice/knapsack/.meta/example.go +++ b/exercises/practice/knapsack/.meta/example.go @@ -0,0 +1,28 @@ +package knapsack + +import "math" + +type item struct { + Weight, Value int +} + +func Knapsack(maximumWeight int, items []item) int { + amountOfItems := len(items) + knapsack := make([][]int, amountOfItems+1) + + for i := range knapsack { + knapsack[i] = make([]int, maximumWeight+1) + } + + for currentItem := 1; currentItem <= amountOfItems; currentItem++ { + for currentItemWeight := 0; currentItemWeight <= maximumWeight; currentItemWeight++ { + if items[currentItem-1].Weight > currentItemWeight { + knapsack[currentItem][currentItemWeight] = knapsack[currentItem-1][currentItemWeight] + } else { + knapsack[currentItem][currentItemWeight] = int(math.Max(float64(knapsack[currentItem-1][currentItemWeight]), float64(items[currentItem-1].Value+knapsack[currentItem-1][currentItemWeight-items[currentItem-1].Weight]))) + } + } + } + + return knapsack[amountOfItems][maximumWeight] +} diff --git a/exercises/practice/knapsack/knapsack.go b/exercises/practice/knapsack/knapsack.go index 657cd2313..92ee26777 100644 --- a/exercises/practice/knapsack/knapsack.go +++ b/exercises/practice/knapsack/knapsack.go @@ -4,6 +4,8 @@ type item struct { Weight, Value int } +// Knapsack takes in a maximum carrying capacity and a collection of items, it should return the best possible value +// of items while remaining within the carrying capacity func Knapsack(maximumWeight int, items []item) int { - return 0 + panic("Please implement the Knapsack() function") } diff --git a/exercises/practice/knapsack/knapsack_test.go b/exercises/practice/knapsack/knapsack_test.go index b5b38497a..3a7271714 100644 --- a/exercises/practice/knapsack/knapsack_test.go +++ b/exercises/practice/knapsack/knapsack_test.go @@ -8,7 +8,7 @@ func TestKnapsack(t *testing.T) { expected := tc.expected if actual != expected { - t.Fatalf("Knapsack(%#v) = %d, want %d", tc.input, actual, tc.expected) + t.Fatalf("Knapsack(%+v) = %d, want %d", tc.input, actual, tc.expected) } } }