Files
hello-algo/ru/codes/javascript/chapter_greedy/fractional_knapsack.js
Yudong Jin 772183705e Add ru version (#1865)
* Add Russian docs site baseline

* Add Russian localized codebase

* Polish Russian code wording

* Update ru code translation.

* Update code translation and chapter covers.

* Fix pythontutor extraction.

* Add README and landing page.

* placeholder of profiles

* Use figures of English version

* Remove chapter paperbook
2026-03-28 04:24:07 +08:00

47 lines
1.8 KiB
JavaScript
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.js
* Created Time: 2023-09-02
* Author: Justin (xiefahit@gmail.com)
*/
/* Предмет */
class Item {
constructor(w, v) {
this.w = w; // Вес предмета
this.v = v; // Стоимость предмета
}
}
/* Дробный рюкзак: жадный алгоритм */
function fractionalKnapsack(wgt, val, cap) {
// Создать список предметов с двумя свойствами: вес и стоимость
const items = wgt.map((w, i) => new Item(w, val[i]));
// Отсортировать по удельной стоимости item.v / item.w в порядке убывания
items.sort((a, b) => b.v / b.w - a.v / a.w);
// Циклический жадный выбор
let res = 0;
for (const item of items) {
if (item.w <= cap) {
// Если оставшейся вместимости достаточно, положить в рюкзак текущий предмет целиком
res += item.v;
cap -= item.w;
} else {
// Если оставшейся вместимости недостаточно, положить в рюкзак часть текущего предмета
res += (item.v / item.w) * cap;
// Свободной вместимости больше не осталось, поэтому выйти из цикла
break;
}
}
return res;
}
/* Driver Code */
const wgt = [10, 20, 30, 40, 50];
const val = [50, 120, 150, 210, 240];
const cap = 50;
const n = wgt.length;
// Жадный алгоритм
const res = fractionalKnapsack(wgt, val, cap);
console.log(`Максимальная стоимость предметов без превышения вместимости рюкзака = ${res}`);