给定一个大小为w
x h
的矩形,和一个要求在这个大矩形内放置n
个相同大小的小矩形,选择dx
和dy
的大小,使得小矩形最优地填满原始矩形。
主要限制条件是所有数字必须为整数。
我目前(JS)的算法如下:
function pack(n, w, h) {
var nx, ny;
var dx = w, dy = h; // initally try one rectangle that fills the box
while (true) {
nx = ~~(w / dx); // see how many times this fits in X
ny = ~~(h / dy); // and in Y
if (nx * ny >= n) break; // they all fit!
if (dx * h >= w * dy) { // look at the aspect ratio
dx = ~~(w / (nx + 1)); // try fitting more horizontally
} else {
dy = ~~(h / (ny + 1)); // or try more vertically
}
if (dx < 1 || dy < 1) {
return; // they can't fit
}
};
return [nx, ny, dx, dy];
};
有更好的算法吗?
[注:这并不是作业——我正在尝试解决如何在画布上绘制“n”个矩阵项,但每个项必须仅使用整像素的问题]。