-
Notifications
You must be signed in to change notification settings - Fork 11
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
20 additions
and
5 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |