RosettaCodeData/Task/Knapsack-problem-Unbounded/D/knapsack-problem-unbounded-2.d

27 lines
1.3 KiB
D
Raw Permalink Normal View History

2015-02-20 00:35:01 -05:00
void main() {
import std.stdio, std.algorithm, std.typecons, std.range, std.conv;
2013-06-05 21:47:54 +00:00
2015-02-20 00:35:01 -05:00
alias Bounty = Tuple!(int,"value", double,"weight", double,"volume");
2013-06-05 21:47:54 +00:00
2015-02-20 00:35:01 -05:00
immutable panacea = Bounty(3000, 0.3, 0.025);
immutable ichor = Bounty(1800, 0.2, 0.015);
immutable gold = Bounty(2500, 2.0, 0.002);
immutable sack = Bounty( 0, 25.0, 0.25);
2013-06-05 21:47:54 +00:00
2015-02-20 00:35:01 -05:00
immutable maxPanacea = min(sack.weight / panacea.weight, sack.volume / panacea.volume).to!int;
immutable maxIchor = min(sack.weight / ichor.weight, sack.volume / ichor.volume).to!int;
immutable maxGold = min(sack.weight / gold.weight, sack.volume / gold.volume).to!int;
2013-06-05 21:47:54 +00:00
2015-02-20 00:35:01 -05:00
immutable best =
2013-06-05 21:47:54 +00:00
cartesianProduct(maxPanacea.iota, maxIchor.iota, maxGold.iota)
2015-02-20 00:35:01 -05:00
.map!(t => tuple(Bounty(t[0] * panacea.value + t[1] * ichor.value + t[2] * gold.value,
t[0] * panacea.weight + t[1] * ichor.weight + t[2] * gold.weight,
t[0] * panacea.volume + t[1] * ichor.volume + t[2] * gold.volume), t))
.filter!(t => t[0].weight <= sack.weight && t[0].volume <= sack.volume)
2013-06-05 21:47:54 +00:00
.reduce!max;
2015-02-20 00:35:01 -05:00
writeln("Maximum value achievable is ", best[0].value);
writefln("This is achieved by carrying (one solution) %d panacea, %d ichor and %d gold", best[1][]);
writefln("The weight to carry is %4.1f and the volume used is %5.3f", best[0][1..$]);
2013-06-05 21:47:54 +00:00
}