Skip to content

Instantly share code, notes, and snippets.

@mrnkr
Created December 5, 2018 14:52
Show Gist options
  • Save mrnkr/0fcfb62e676e4db207f72e9a249686a2 to your computer and use it in GitHub Desktop.
Save mrnkr/0fcfb62e676e4db207f72e9a249686a2 to your computer and use it in GitHub Desktop.
Dynamic programming exercise - Build a necklace with the greatest value without surpassing the maximum allowed weight (modification of the 0/1 knapsack problem)
import Foundation
func max(a: Int, b: Int) -> Int {
return a > b ? a : b
}
func necklace(pearls: [[Int]]) -> [[Int]] {
var res = Array.init(repeating: Array.init(repeating: 0, count: 151), count: pearls.count)
var ret: [[Int]] = []
for i in 0...150 {
let weight = pearls[0][0]
let value = pearls[0][1]
res[0][i] = weight <= i ? value : 0
}
for i in 1...pearls.count - 1 {
for j in pearls[i][0]...150 {
let weight = pearls[i][0]
let value = pearls[i][1]
res[i][j] = max(res[i - 1][j], res[i - 1][j - weight] + value)
}
}
var i = pearls.count - 1
var j = 150
while i >= 0 && j >= 0 {
if i > 0 {
let mayorQueArriba = res[i][j] > res[i - 1][j]
if mayorQueArriba {
ret.append(pearls[i])
j = j - pearls[i][0]
i = i - 1
} else {
i = i - 1
}
} else {
if res[i][j] == 0 {
break
} else {
ret.append(pearls[i])
j = j - pearls[i][0]
}
}
}
return ret
}
let cnt = Int.random(in: 0...150)
var pearls: [[Int]] = Array.init(repeating: Array.init(repeating: 0, count: 2), count: cnt)
for i in 0...pearls.count - 1 {
pearls[i][0] = Int.random(in: 0...25)
pearls[i][1] = Int.random(in: 1...500)
}
necklace(pearls: pearls)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment