-
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
23 additions
and
22 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,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 | ||
} |