Created
May 7, 2019 06:12
-
-
Save derekli66/d2bd267ddd53c96af7d04491f522512a to your computer and use it in GitHub Desktop.
This gist is the practice of knapsack problem. The solution without optimization by using memoization.
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
import Foundation | |
func knapsack(_ weights: Array<Int>,_ values: Array<Int>,_ index: Int,_ remainingWeight: Int) -> Int { | |
if (index < 0) { return 0 } | |
var choosedValue: Int = 0 | |
if (remainingWeight >= weights[index]) { | |
// Choose | |
choosedValue = values[index] + knapsack(weights, values, index - 1, remainingWeight - weights[index]) | |
} | |
// Not choose | |
let notChoosedValue = knapsack(weights, values, index - 1, remainingWeight) | |
return max(choosedValue, notChoosedValue) | |
} | |
let weights = [2, 5, 3] | |
let values = [10, 1, 2] | |
let weightLimit = 2 | |
let mostValue = knapsack(weights, values, weights.count - 1, weightLimit) | |
print("[Knapsack] The most value can be carried is \(mostValue)") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment