A spice trader walks through a market with a bag that holds capacity kilograms. Each stall sells one spice: a whole sack weighs weight kilograms and is worth value. Spice can be scooped, so the trader may take any part of a sack, and a part is worth the same fraction of the sack's value. What is the most valuable load?
Each item is an object { weight, value }. Write fractionalKnapsack(items, capacity).
It returns { value, taken }, where taken[i] is how many kilograms of item i go into the bag (from 0 up to items[i].weight), and value is the total worth of that load: the sum of items[i].value * taken[i] / items[i].weight. taken has one entry per item, in input order.
Rules:
If items is not an array, an item is not an object, or a weight, value or capacity is not a finite number, throw a TypeError. If a weight is 0 or less, a value is negative, or capacity is negative, throw a RangeError.
The total of taken must not exceed capacity. When several items share the best value per kilogram, any split between them is fine; the tests check that the load is valid and that value is the best possible, within 1e-6.
With no items or a capacity of 0, value is 0 and every entry of taken is 0.
Do not modify items.
There can be 200,000 items. Scanning all of them for the best remaining one before every scoop is quadratic; aim for O(n log n).