You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
hello-algo/codes/swift/chapter_greedy/fractional_knapsack.swift

58 lines
1.5 KiB

/**
* File: fractional_knapsack.swift
* Created Time: 2023-09-03
* Author: nuomi1 (nuomi1@qq.com)
*/
/* */
class Item {
var w: Int //
var v: Int //
init(w: Int, v: Int) {
self.w = w
self.v = v
}
}
/* */
func fractionalKnapsack(wgt: [Int], val: [Int], cap: Int) -> Double {
//
var items = zip(wgt, val).map { Item(w: $0, v: $1) }
// item.v / item.w
items.sort { -(Double($0.v) / Double($0.w)) < -(Double($1.v) / Double($1.w)) }
//
var res = 0.0
var cap = cap
for item in items {
if item.w <= cap {
//
res += Double(item.v)
cap -= item.w
} else {
//
res += Double(item.v) / Double(item.w) * Double(cap)
//
break
}
}
return res
}
@main
enum FractionalKnapsack {
/* Driver Code */
static func main() {
//
let wgt = [10, 20, 30, 40, 50]
//
let val = [50, 120, 150, 210, 240]
//
let cap = 50
//
let res = fractionalKnapsack(wgt: wgt, val: val, cap: cap)
print("不超过背包容量的最大物品价值为 \(res)")
}
}