main
Jason Staten 9 months ago
commit 5bfc228c92

@ -0,0 +1,8 @@
module git.jxs.me/r/knapsack
go 1.20
require (
github.com/carlmjohnson/be v0.23.1
golang.org/x/exp v0.0.0-20230817173708-d852ddb80c63
)

@ -0,0 +1,4 @@
github.com/carlmjohnson/be v0.23.1 h1:lmzkNRv25/mptDQ1ywXMvgQ6u6IZMYna/KHWAquM1II=
github.com/carlmjohnson/be v0.23.1/go.mod h1:KAgPUh0HpzWYZZI+IABdo80wTgY43YhbdsiLYAaSI/Q=
golang.org/x/exp v0.0.0-20230817173708-d852ddb80c63 h1:m64FZMko/V45gv0bNmrNYoDEq8U5YUhetc9cBWKS1TQ=
golang.org/x/exp v0.0.0-20230817173708-d852ddb80c63/go.mod h1:0v4NqG35kSWCMzLaMeX+IQrlSnVE/bqGSyC2cz/9Le8=

@ -0,0 +1,54 @@
package main
import "golang.org/x/exp/constraints"
type Book struct {
Weight uint
Value uint
}
func MaxValue(capacity uint, books []Book) uint {
if capacity == 0 {
return 0
}
if len(books) == 0 {
return 0
}
book := books[0]
return Max(
book.Value+MaxValue(capacity-book.Weight, books[1:]),
MaxValue(capacity, books[1:]),
)
}
func main() {
println("Did it")
}
func Max[T constraints.Ordered](args ...T) T {
if len(args) == 0 {
return *new(T) // zero value of T
}
if isNan(args[0]) {
return args[0]
}
max := args[0]
for _, arg := range args[1:] {
if isNan(arg) {
return arg
}
if arg > max {
max = arg
}
}
return max
}
func isNan[T constraints.Ordered](arg T) bool {
return arg != arg
}

@ -0,0 +1,37 @@
package main_test
import (
"testing"
ks "git.jxs.me/r/knapsack"
"github.com/carlmjohnson/be"
)
func TestDefaultsZero(t *testing.T) {
result := ks.MaxValue(0, []ks.Book{})
be.Equal(t, 0, result)
}
func TestFitsOne(t *testing.T) {
result := ks.MaxValue(1, []ks.Book{{Weight: 1, Value: 2}})
be.Equal(t, 2, result)
}
func TestFitsHigher(t *testing.T) {
result := ks.MaxValue(1, []ks.Book{
{Weight: 1, Value: 2},
{Weight: 1, Value: 3},
})
be.Equal(t, 3, result)
}
func TestPrefersMultiple(t *testing.T) {
result := ks.MaxValue(3, []ks.Book{
{Weight: 3, Value: 4},
{Weight: 1, Value: 1},
{Weight: 1, Value: 2},
{Weight: 1, Value: 3},
})
be.Equal(t, 6, result)
}
Loading…
Cancel
Save