Knapsack problem/Continuous: Difference between revisions
Content added Content deleted
(Added Erlang) |
(Updated first D entry) |
||
Line 338: | Line 338: | ||
=={{header|D}}== |
=={{header|D}}== |
||
<lang d>import std.stdio, std.algorithm, std.string |
<lang d>import std.stdio, std.algorithm, std.string; |
||
struct Item { |
struct Item { |
||
Line 344: | Line 344: | ||
real amount, value; |
real amount, value; |
||
@property real valuePerKG() const pure nothrow { |
@property real valuePerKG() @safe const pure nothrow { |
||
return value / amount; |
return value / amount; |
||
} |
} |
||
Line 354: | Line 354: | ||
} |
} |
||
real |
real sumBy(string field)(in Item[] items) @safe pure nothrow { |
||
return reduce!("a + b." ~ field)(0.0L, items); |
return reduce!("a + b." ~ field)(0.0L, items); |
||
} |
} |
||
void main() { |
void main() { |
||
const items = [Item("beef", 3.8, 36.0), |
|||
Item("pork", 5.4, 43.0), |
|||
Item("ham", 3.6, 90.0), |
|||
Item("greaves", 2.4, 45.0), |
|||
Item("flitch", 4.0, 30.0), |
|||
Item("brawn", 2.5, 56.0), |
|||
Item("welt", 3.7, 67.0), |
|||
Item("salami", 3.0, 95.0), |
|||
Item("sausage", 5.9, 98.0)] |
|||
.schwartzSort!(it => -it.valuePerKG) |
|||
.release; |
|||
const items = raw.sort!q{a.valuePerKG > b.valuePerKG}.release; |
|||
immutable(Item)[] chosen; |
immutable(Item)[] chosen; |
||
real space = 15.0; |
real space = 15.0; |
||
foreach (item; items) |
foreach (const item; items) |
||
if (item.amount < space) { |
if (item.amount < space) { |
||
chosen ~= item; |
chosen ~= item; |
||
Line 385: | Line 384: | ||
writefln("%10s %7s %7s %7s", "ITEM", "AMOUNT", "VALUE", "$/unit"); |
writefln("%10s %7s %7s %7s", "ITEM", "AMOUNT", "VALUE", "$/unit"); |
||
writefln("%(%s\n%)", chosen); |
writefln("%(%s\n%)", chosen); |
||
Item("TOTAL", chosen. |
Item("TOTAL", chosen.sumBy!"amount", chosen.sumBy!"value").writeln; |
||
}</lang> |
}</lang> |
||
{{out}} |
{{out}} |