dynamic programming!

main
Jason Staten 9 months ago
parent 9e586eca69
commit 31d2aed844

@ -1,13 +1,15 @@
package main
import "golang.org/x/exp/constraints"
import (
"golang.org/x/exp/constraints"
)
type Book struct {
Weight uint
Value uint
Weight int
Value int
}
func MaxValue(capacity uint, books []Book) uint {
func MaxValue(capacity int, books []Book) int {
if capacity == 0 {
return 0
}
@ -25,6 +27,21 @@ func MaxValue(capacity uint, books []Book) uint {
return Max(withBook, withoutBook)
}
func DynamicMaxValue(capacity int, books []Book) int {
memo := make([]int, capacity+1)
for _, book := range books {
for c := capacity; c >= 0; c-- {
if book.Weight <= c {
memo[c] = Max(memo[c], memo[c-book.Weight]+book.Value)
}
}
}
return memo[capacity]
}
func main() {
println("Did it")
}

@ -13,6 +13,11 @@ func TestDefaultsZero(t *testing.T) {
be.Equal(t, 0, result)
}
func TestEmpty(t *testing.T) {
result := ks.DynamicMaxValue(1, []ks.Book{})
be.Equal(t, 0, result)
}
func TestFitsOne(t *testing.T) {
result := ks.MaxValue(1, []ks.Book{
{Weight: 1, Value: 2},
@ -45,3 +50,48 @@ func TestIgnoresTooBig(t *testing.T) {
})
be.Equal(t, 1, result)
}
// Dynamic
func TestDynamicDefaultsZero(t *testing.T) {
result := ks.DynamicMaxValue(0, []ks.Book{})
be.Equal(t, 0, result)
}
func TestDynamicFitsOne(t *testing.T) {
result := ks.DynamicMaxValue(1, []ks.Book{
{Weight: 1, Value: 2},
})
be.Equal(t, 2, result)
}
func TestDynamicFitsHigher(t *testing.T) {
result := ks.DynamicMaxValue(1, []ks.Book{
{Weight: 1, Value: 3},
{Weight: 1, Value: 2},
})
be.Equal(t, 3, result)
}
func TestDynamicPrefersMultiple(t *testing.T) {
result := ks.DynamicMaxValue(3, []ks.Book{
{Weight: 3, Value: 4},
{Weight: 1, Value: 1},
{Weight: 1, Value: 2},
{Weight: 1, Value: 3},
})
be.Equal(t, 6, result)
}
func TestDynamicIgnoresTooBig(t *testing.T) {
result := ks.DynamicMaxValue(1, []ks.Book{
{Weight: 10, Value: 4},
{Weight: 1, Value: 1},
})
be.Equal(t, 1, result)
}
func TestDynamicEmpty(t *testing.T) {
result := ks.DynamicMaxValue(1, []ks.Book{})
be.Equal(t, 0, result)
}

Loading…
Cancel
Save