Skip to content

Commit

Permalink
solve knapsack
Browse files Browse the repository at this point in the history
  • Loading branch information
rootulp committed Aug 13, 2024
1 parent 2d6c968 commit 8d0ff58
Showing 1 changed file with 23 additions and 22 deletions.
45 changes: 23 additions & 22 deletions go/knapsack/knapsack.go
Original file line number Diff line number Diff line change
@@ -1,35 +1,36 @@
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) (maxValue int) {
sorted := sortItemsByValuePerWeight(items)
fmt.Printf("sorted: %v\n", sorted)
currentWeight := maximumWeight
for _, item := range sorted {
if item.Weight <= currentWeight {
currentWeight -= item.Weight
maxValue += item.Value
}
func Knapsack(maximumWeight int, items []Item) (total int) {
currentValue := 0
currentWeight := 0
return knapsack(items, currentValue, currentWeight, maximumWeight)
}

func knapsack(items []Item, value int, weight int, maxWeight int) (total int) {
if len(items) == 0 {
return value
}
return maxValue
item := items[0]
totalWithItem := knapsack(items[1:], value+item.Value, weight+item.Weight, maxWeight)
totalWithoutItem := knapsack(items[1:], value, weight, maxWeight)

// If the current item is too heavy, return the total without the current item
if weight+item.Weight > maxWeight {
return totalWithoutItem
}
return max(totalWithItem, totalWithoutItem)
}

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
func max(a int, b int) int {
if a > b {
return a
}
return b
}

0 comments on commit 8d0ff58

Please sign in to comment.