Skip to content

Commit

Permalink
create working example and fleshing out the Knapsack function
Browse files Browse the repository at this point in the history
  • Loading branch information
jesse-kroon committed Feb 1, 2024
1 parent 91e57c6 commit c7e2c71
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 2 deletions.
28 changes: 28 additions & 0 deletions exercises/practice/knapsack/.meta/example.go
Original file line number Diff line number Diff line change
@@ -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]
}
4 changes: 3 additions & 1 deletion exercises/practice/knapsack/knapsack.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
2 changes: 1 addition & 1 deletion exercises/practice/knapsack/knapsack_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
}

0 comments on commit c7e2c71

Please sign in to comment.