hello-algo/codes/swift/chapter_greedy/fractional_knapsack.swift
nuomi1 8d5e84f70a
Feature/chapter greedy swift (#720)
* feat: add Swift codes for greedy_algorithm article

* feat: add Swift codes for fractional_knapsack_problem article

* feat: add Swift codes for max_capacity_problem article

* feat: add Swift codes for max_product_cutting_problem article
2023-09-03 19:09:45 +08:00

57 lines
1.5 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* File: fractional_knapsack.swift
* Created Time: 2023-09-03
* Author: nuomi1 (nuomi1@qq.com)
*/
//
struct 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(by: { -(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)")
}
}