微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

可视化并计算一个更大的矩形可以容纳多少个矩形/正方形更新:装箱

如何解决可视化并计算一个更大的矩形可以容纳多少个矩形/正方形更新:装箱

我需要创建一个函数来计算有多少个给定/固定宽度和高度的矩形/正方形适合一个更大的固定宽度和高度的矩形。方向应该无关紧要。目标是最好地利用给定大小的空间。

这是我尝试过的:https://codepen.io/mzmarkib/pen/vYXbayY

编辑/更新:我尝试使用名为 Shelf-pack 的库的另一种方法 但仍然有空格,不知道我做错了什么。请看一下: CodePen Link

HTML

<div class="plate"></div>

CSS

* {
  margin: 0;
  padding: 0;
  Box-sizing: border-Box;
}
body {
  display: flex;
  height: 100vh;
}
.plate {
  border: 2px solid red;
  margin: auto;
}
.page {
  padding: 5px;
  border: 1px solid blue;
  float: left;
}

JAVASCRIPT

//sizes for pages(blue rectangles)
let pages = {
  a3: { w: 29.7,h: 42 },a4: { w: 21,h: 29.7 },custom: { w: 33,h: 20 },custom: { w: 5,h: 5 }
};

const PLATE_SIZE = { w: 100,h: 70 }; //demesions of the plate (red rectangle)
const SCALE = 10; //scale for representation

const plate = document.querySelector(".plate");
plate.style.width = PLATE_SIZE.w * SCALE + "px";
plate.style.height = PLATE_SIZE.h * SCALE + "px";
const plate_boundary = plate.getBoundingClientRect();

//Adds a page(blue rectangle) to the plate(red rectangle),then checks whether it's out of bounds,if yes removes the page(blue rectangle) and returns false
function addPage(w,h,name) {
  page = document.createElement("div");
  page.innerHTML = name;
  page.classList.add("page");
  page.style.width = w * SCALE + "px";
  page.style.height = h * SCALE + "px";

  plate.appendChild(page);

  if (!isWithinBoundary(page)) {
    plate.removeChild(page);
    return false;
  } else {
    return true;
  }
}
//check if a page(blue rectangle) is out of bounds
function isWithinBoundary(page) {
  const rect = page.getBoundingClientRect();
  return (
    rect.top >= 0 &&
    rect.left >= 0 &&
    rect.bottom <= plate_boundary.bottom &&
    rect.right <= plate_boundary.right
  );
}
//recursively add pages to the plate (red rectangle)
function fillPages(pages) {
  for (const page in pages) {
    const { w,h } = pages[page];
    while (addPage(w,page)) {
      continue;
    }
    while (addPage(h,w,page)) {
      continue;
    }
  }
}

fillPages(pages); //execution

使用我的方法,即使有空白区域,它也不会填充某些区域的矩形。

如果这是一个愚蠢的问题,请原谅我。如果没有,请指导我如何解决这个问题。无论哪种方式,提前致谢...

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。