Skip to content

Instantly share code, notes, and snippets.

@edalquist
Last active April 22, 2020 05:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edalquist/555f3579cce18126c45698fb9036c0d6 to your computer and use it in GitHub Desktop.
Save edalquist/555f3579cce18126c45698fb9036c0d6 to your computer and use it in GitHub Desktop.
var kerf = 0.125;
var stock_length = 96;
function arraySum(arr) {
var sum = 0;
for (var i = 0, len = arr.length; i < len; sum += arr[i++]);
sum += (arr.length * kerf);
return sum;
}
/**
* Simple Sorted Best Fit linear bin packing algorithm to figure out cut lists
* and material needs.
*/
function calculateCutList(cut_array) {
var stock_array = [];
// Sort cuts largest to smallest
cut_array.sort((a, b) => b - a);
cut_array.forEach(cut => {
// Track reference to best-fit stock array and the leftover space after this cut is fit
var bestStock = null;
var bestLeftover = stock_length;
stock_array.forEach(stock => {
// Calculate how much space is used and what is available
var used = arraySum(stock);
var avail = stock_length - used - kerf;
// If there is space available for the cut
if (cut <= avail) {
var leftover = avail - cut;
// If the leftover is less than the existing best stock
if (leftover < bestLeftover) {
// Capture ref to stock array and leftover space
bestStock = stock;
bestLeftover = leftover;
}
}
});
// If no bestStock is found add a new stock with the cut
if (bestStock == null) {
stock_array.push([cut]);
} else {
// Otherwise add the cut to the best fitting stock
bestStock.push(cut);
}
});
stock_array.sort((a, b) => arraySum(b) - arraySum(a));
stock_array.forEach(stock => console.log(stock));
}
console.log("2x6");
calculateCutList([32.5,32.5,32.5,32.5,27,27,27,27,29,29,72,72,34.5,34.5]);
console.log("2x4");
calculateCutList([25,25,25,25,25,34,34,34,34,57.375,57.375,72,41,33,33,19.625,19.625,10.5,10.5,17.5,17.5,29,29,5.1875,5.1875,5.1875,5.1875]);
console.log("1x4");
calculateCutList([2.25,2.25,23.625,23.625,36,36,41,73.5,20.5]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment