#!/usr/bin/ruby

#
## https://rosettacode.org/wiki/Knapsack_problem/Continuous
#

var 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],
].sort {|a,b| b[2]/b[1] <=> a[2]/a[1] };
 
var (limit, value) = (15, 0);
print "Item   Fraction Weight Value\n";
 
items.each { |item|
        var ratio = (item[1] > limit ? limit/item[1] : 1);
        value += item[2]*ratio;
        limit -= item[1];
        if (ratio == 1) {
            printf("%-8s %-4s %7.2f %6.2f\n", item[0], 'all', item[1], item[2]);
        }
        else {
            printf("%-8s %-4.2f %7.2f %6.2f\n", item[0], ratio, item[1]*ratio, item[2]*ratio);
            break;
        }
};
 
say "#{'-'*28}\ntotal value: #{'%.14g' % value }";
