Time for an 2014 update…

This commit is contained in:
Ingy döt Net 2014-01-17 05:32:22 +00:00
parent 372c577f83
commit 09687c4926
2520 changed files with 34227 additions and 7318 deletions

View file

@ -1,10 +1,10 @@
import std.stdio, std.algorithm, std.string, std.conv;
import std.stdio, std.algorithm, std.string;
struct Item {
string name;
real amount, value;
@property real valuePerKG() const pure nothrow {
@property real valuePerKG() @safe const pure nothrow {
return value / amount;
}
@ -14,27 +14,26 @@ struct Item {
}
}
real sum(string field)(in Item[] items) pure nothrow {
real sumBy(string field)(in Item[] items) @safe pure nothrow {
return reduce!("a + b." ~ field)(0.0L, items);
}
void main() {
Item[] raw = [{"beef", 3.8, 36.0},
{"pork", 5.4, 43.0},
{"ham", 3.6, 90.0},
{"greaves", 2.4, 45.0},
{"flitch", 4.0, 30.0},
{"brawn", 2.5, 56.0},
{"welt", 3.7, 67.0},
{"salami", 3.0, 95.0},
{"sausage", 5.9, 98.0}];
// Reverse sorted by Value per amount.
const items = raw.sort!q{a.valuePerKG > b.valuePerKG}.release;
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;
immutable(Item)[] chosen;
real space = 15.0;
foreach (item; items)
foreach (const item; items)
if (item.amount < space) {
chosen ~= item;
space -= item.amount;
@ -45,5 +44,5 @@ void main() {
writefln("%10s %7s %7s %7s", "ITEM", "AMOUNT", "VALUE", "$/unit");
writefln("%(%s\n%)", chosen);
Item("TOTAL", chosen.sum!"amount", chosen.sum!"value").writeln;
Item("TOTAL", chosen.sumBy!"amount", chosen.sumBy!"value").writeln;
}

View file

@ -0,0 +1,36 @@
-module( knapsack_problem_continuous ).
-export( [price_per_weight/1, select/2, task/0] ).
price_per_weight( Items ) -> [{Name, Weight, Price / Weight} || {Name, Weight, Price} <-Items].
select( Max_weight, Items ) ->
{_Remains, Selected_items} = lists:foldr( fun select_until/2, {Max_weight, []}, lists:keysort(3, Items) ),
Selected_items.
task() ->
Items = items(),
io:fwrite( "The robber takes the following to maximize the value~n" ),
[io:fwrite("~.2f of ~p~n", [Weight, Name]) || {Name, Weight} <- select( 15, price_per_weight(Items) )].
items() ->
[{"beef", 3.8, 36},
{"pork", 5.4, 43},
{"ham", 3.6, 90},
{"greaves", 2.4, 45},
{"flitch", 4.0, 30},
{"brawn", 2.5, 56},
{"welt", 3.7 , 67},
{"salami", 3.0, 95},
{"sausage", 5.9 , 98}
].
select_until( {Name, Weight, _Price}, {Remains, Acc} ) when Remains > 0 ->
Selected_weight = select_until_weight( Weight, Remains ),
{Remains - Selected_weight, [{Name, Selected_weight} | Acc]};
select_until( _Item, Acc ) -> Acc.
select_until_weight( Weight, Remains ) when Weight < Remains -> Weight;
select_until_weight( _Weight, Remains ) -> Remains.