mirror of
https://github.com/krahets/hello-algo.git
synced 2026-08-14 04:30:58 +00:00
2778a6f9c7
* Review the EN heading format. * Fix pythontutor headings. * Fix pythontutor headings. * bug fixes * Fix headings in **/summary.md * Revisit the CN-to-EN translation for Python code using Claude-4.5 * Revisit the CN-to-EN translation for Java code using Claude-4.5 * Revisit the CN-to-EN translation for Cpp code using Claude-4.5. * Fix the dictionary. * Fix cpp code translation for the multipart strings. * Translate Go code to English. * Update workflows to test EN code. * Add EN translation for C. * Add EN translation for CSharp. * Add EN translation for Swift. * Trigger the CI check. * Revert. * Update en/hash_map.md * Add the EN version of Dart code. * Add the EN version of Kotlin code. * Add missing code files. * Add the EN version of JavaScript code. * Add the EN version of TypeScript code. * Fix the workflows. * Add the EN version of Ruby code. * Add the EN version of Rust code. * Update the CI check for the English version code. * Update Python CI check. * Fix cmakelists for en/C code. * Fix Ruby comments
51 lines
1.5 KiB
Kotlin
51 lines
1.5 KiB
Kotlin
/**
|
|
* File: fractional_knapsack.kt
|
|
* Created Time: 2024-01-25
|
|
* Author: curtishd (1023632660@qq.com)
|
|
*/
|
|
|
|
package chapter_greedy
|
|
|
|
/* Item */
|
|
class Item(
|
|
val w: Int, // Item
|
|
val v: Int // Item value
|
|
)
|
|
|
|
/* Fractional knapsack: Greedy algorithm */
|
|
fun fractionalKnapsack(wgt: IntArray, _val: IntArray, c: Int): Double {
|
|
// Create item list with two attributes: weight, value
|
|
var cap = c
|
|
val items = arrayOfNulls<Item>(wgt.size)
|
|
for (i in wgt.indices) {
|
|
items[i] = Item(wgt[i], _val[i])
|
|
}
|
|
// Sort by unit value item.v / item.w from high to low
|
|
items.sortBy { item: Item? -> -(item!!.v.toDouble() / item.w) }
|
|
// Loop for greedy selection
|
|
var res = 0.0
|
|
for (item in items) {
|
|
if (item!!.w <= cap) {
|
|
// If remaining capacity is sufficient, put the entire current item into the knapsack
|
|
res += item.v
|
|
cap -= item.w
|
|
} else {
|
|
// If remaining capacity is insufficient, put part of the current item into the knapsack
|
|
res += item.v.toDouble() / item.w * cap
|
|
// No remaining capacity, so break out of the loop
|
|
break
|
|
}
|
|
}
|
|
return res
|
|
}
|
|
|
|
/* Driver Code */
|
|
fun main() {
|
|
val wgt = intArrayOf(10, 20, 30, 40, 50)
|
|
val _val = intArrayOf(50, 120, 150, 210, 240)
|
|
val cap = 50
|
|
|
|
// Greedy algorithm
|
|
val res = fractionalKnapsack(wgt, _val, cap)
|
|
println("Maximum item value not exceeding knapsack capacity is $res")
|
|
} |