Created
July 10, 2018 08:02
-
-
Save amulyakashyap09/695f44d5354debf2b28ad5d123aaf72f to your computer and use it in GitHub Desktop.
maximization knapsack solution using Go (Greedy Approach)
This file contains hidden or 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
package main | |
import ( | |
"fmt" | |
"errors" | |
) | |
func getMax(arr []int) int { | |
var max int = 0 | |
var index int = 0 | |
for i, val := range arr { | |
if max < val{ | |
max = val | |
index = i | |
} | |
} | |
return index | |
} | |
func main() { | |
var values []int = []int{10, 5, 15, 7, 6, 18, 3} | |
var items []int = []int{2, 3, 5, 7, 1, 4, 1} | |
var valuePerItem []int | |
var valuePerItemBak []int | |
var capacity int = 15 | |
if len(items) != len(values){ | |
fmt.Println("=======error==", errors.New("Invalid value or items.")) | |
}else { | |
for i:=0; i<len(items); i++ { | |
val := values[i]/items[i] | |
valuePerItem = append(valuePerItem, val) | |
} | |
valuePerItemBak = append(valuePerItemBak, valuePerItem...) | |
var sumVal int = 0 | |
var sumItem int = 0 | |
for sumItem <= capacity { | |
index := getMax(valuePerItem) | |
valuePerItem[index] = 0 | |
sumVal += values[index] | |
sumItem += items[index] | |
} | |
fmt.Println("values : ", values) | |
fmt.Println("items : ", items) | |
fmt.Println("valuePerItem : ", valuePerItemBak) | |
fmt.Println("sumVal : ", sumVal) | |
fmt.Println("sumItem : ", sumItem) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment