JSFiddle - React, Tailwind, and code Playground
bin packing test
by Csaba Hellinger
HTML
<div id="display">
</div>
CSS
body {
margin: 0;
}
#display {
/*width: 220px;*/
padding: 10px;
background-color: #A0A0A0;
}
.table {
position: relative;
margin-bottom: 10px;
background-color: #606060;
}
.rect {
position: absolute;
background-color: #B3A26E;
border: 1px solid #E0E0E0;
box-sizing: border-box;
}
JavaScript
/*
- vágás vastagság: 4mm
- mértékegység: mm, egész
- out: wxh bele a darabba
*/
var tabSize = {width: 200, height: 150},
rects = [
{width: 120, height: 140},
{width: 80, height: 100},
{width: 70, height: 50},
{width: 180, height: 80},
{width: 80, height: 70},
{width: 50, height: 60},
{width: 70, height: 30},
{width: 40, height: 40},
],
tables,
$display = $('#display');
function log() {
var i, rect, str = '';
for (i=0; i<rects.length; i++) {
rect = rects[i];
str += ' { w:' + rect.width + ', h:' + rect.height + ', a:' + rect.area + ' } \n';
}
console.log('[\n' + str + '\n]');
}
// area
rects.forEach(function (rect) {
rect.area = rect.width * rect.height;
});
// sort
rects.sort(function (a, b) {
return b.area - a.area;
});
function rectCoords(left, top, width, height) {
return { x0: left, y0: top, x1: left + width, y1: top + height };
}
function between(value, min, max) {
return (min < value && value < max);
}
function inside(x, y, coords) {
return between(x, coords.x0, coords.x1) && between(y, coords.y0, coords.y1);
}
function hitTest(c1, c2) {
return (
inside(c2.x0, c2.y0, c1) ||
inside(c2.x0, c2.y1, c1) ||
inside(c2.x1, c2.y0, c1) ||
inside(c2.x1, c2.y1, c1)
);
}
function findPlace(table, rect) {
var i, place, coords, iPrev, prev, hit;
for (i=0; i<table.places.length; i++) {
place = table.places[i];
console.log(' PLACE', place);
// table bounds check
coords = rectCoords(place.left, place.top, rect.width, rect.height);
if (coords.x1 > tabSize.width || coords.y1 > tabSize.height) {
console.log(' OUT');
continue;
}
// hit test with the previous rects
hit = false;
for (iPrev=0; iPrev<table.rects.length; iPrev++) {
prev = table.rects[iPrev];
prevCoords = rectCoords(prev.left, prev.top, prev.width, prev.height);
...