Skip to content

Instantly share code, notes, and snippets.

@dawnerd
Created March 4, 2011 00:12
Show Gist options
  • Save dawnerd/853889 to your computer and use it in GitHub Desktop.
Save dawnerd/853889 to your computer and use it in GitHub Desktop.
Plane cargo challenge
var items = {
'LJS93K': {
pounds: 1300,
cost: 10500
},
'J38ZZ9': {
pounds: 700,
cost: 4750
},
'HJ394L': {
pounds: 200,
cost: 3250
},
'O1IE82': {
pounds: 75,
cost: 10250
}
},
minWeight = 1250,
removedWeight = 0,
remainingWeight = minWeight,
removedCost = 0,
costPerPound = [];
for(item in items) {
var sku = item, item = items[item];
costPerPound.push({cost: Math.ceil(item.cost/item.pounds), sku: sku });
}
costPerPound.sort(function(a,b) {
if(a.cost<b.cost) return -1;
if(a.cost>b.cost) return 1;
return 0;
});
for(var i = 0, c = costPerPound.length; i < c; i++) {
var totalWeight = 0, totalCost = 0, item = items[costPerPound[i].sku];
if(removedWeight < minWeight) {
totalWeight = (item.pounds <= remainingWeight) ? item.pounds : remainingWeight;
totalCost = totalWeight * costPerPound[i].cost;
removedCost += totalCost;
removedWeight += totalWeight;
remainingWeight -= totalWeight;
}
}
print(removedCost);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment