Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
rootulp committed Aug 13, 2024
1 parent cb0b198 commit 2d6c968
Showing 1 changed file with 20 additions and 5 deletions.
25 changes: 20 additions & 5 deletions go/knapsack/knapsack.go
Original file line number Diff line number Diff line change
@@ -1,20 +1,35 @@
package knapsack

import (
"fmt"
"sort"
)

type Item struct {
Weight, Value int
}

// Knapsack takes in a maximum carrying capacity and a collection of items
// and returns the maximum value that can be carried by the knapsack
// given that the knapsack can only carry a maximum weight given by maximumWeight
func Knapsack(maximumWeight int, items []Item) int {
func Knapsack(maximumWeight int, items []Item) (maxValue int) {
sorted := sortItemsByValuePerWeight(items)
fmt.Printf("sorted: %v\n", sorted)
currentWeight := maximumWeight
total := 0
for _, item := range items {
for _, item := range sorted {
if item.Weight <= currentWeight {
currentWeight -= item.Weight
total += item.Value
maxValue += item.Value
}
}
return total
return maxValue
}

func sortItemsByValuePerWeight(items []Item) []Item {
sort.Slice(items, func(i, j int) bool {
iValuePerWeight := float64(items[i].Value) / float64(items[i].Weight)
jValuePerWeight := float64(items[j].Value) / float64(items[j].Weight)
return iValuePerWeight > jValuePerWeight
})
return items
}

0 comments on commit 2d6c968

Please sign in to comment.