function ksack(values, weights, capacity) { var load = 0; var i = 0; var v = 0; while (load < capacity && i < weights.length) { if (weights[i] <= (capacity - load)) { v += values[i]; load += weights[i]; } else { var r = (capacity - load) / weights[i]; v += r * values[i]; load += weights[i]; } ++i; } return v; } var items = [ "A", "B", "C", "D" ]; var values = [ 50, 140, 60, 60 ]; var weights = [ 5, 20, 10, 12 ]; var capacity = 30; document.write(ksack(values, weights, capacity)); // 显示 220
原文:http://www.cnblogs.com/feile/p/5399435.html