Last active
September 22, 2019 11:35
-
-
Save YounesRahimi/86311e66e5e2be769786ec84cc02f108 to your computer and use it in GitHub Desktop.
A sequential implementation of knapsack problem
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" | |
| "log" | |
| "math/rand" | |
| "time" | |
| ) | |
| type Matrix [][]int | |
| func (m Matrix) String() string { | |
| s := fmt.Sprintf("%v", m[0]) | |
| for i := 1; i < len(m); i++ { | |
| s += "\n" + fmt.Sprintf("%v", m[i]) | |
| } | |
| return s | |
| } | |
| func main() { | |
| //maxW := 15 | |
| //vs := []int{10, 7, 5, 4} | |
| //ws := []int{6, 5, 4, 2} | |
| randNum := 10000 | |
| maxW := randNum * 2 | |
| vs := make([]int, 0) | |
| ws := make([]int, 0) | |
| rand3 := rand.New(rand.NewSource(time.Now().Unix())) | |
| for i := 0; i < randNum/2; i++ { | |
| vs = append(vs, rand3.Intn(randNum/10)) | |
| ws = append(ws, rand3.Intn(randNum/5)) | |
| } | |
| start := time.Now() | |
| knapsack := printKnapsack(vs, ws, maxW) | |
| elapsed := time.Since(start) | |
| log.Printf("\nKnapstack took %s", elapsed) | |
| for i := range knapsack { | |
| fmt.Print(i, " ") | |
| } | |
| } | |
| // Max returns the larger of x or y. | |
| func Max(x, y int) int { | |
| if x < y { | |
| return y | |
| } | |
| return x | |
| } | |
| func printKnapsack(vs []int, ws []int, maxWeight int) <-chan int { | |
| mat := make(Matrix, len(vs)+1) | |
| for i := range mat { | |
| mat[i] = make([]int, maxWeight+1) | |
| } | |
| for item := 0; item < len(ws); item++ { | |
| for w := 1; w <= maxWeight; w++ { | |
| if ws[item] > w { | |
| mat[item+1][w] = mat[item][w] | |
| } else { | |
| mat[item+1][w] = Max(mat[item][w], vs[item]+mat[item][w-ws[item]]) | |
| } | |
| } | |
| } | |
| //fmt.Println(mat) | |
| c := make(chan int) | |
| go func() { | |
| for w, item := maxWeight, len(ws); w >= 1 && item >= 1; item-- { | |
| if mat[item][w] != mat[item-1][w] { | |
| c <- item | |
| w -= ws[item-1] | |
| } | |
| } | |
| close(c) | |
| }() | |
| return c | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment