algorithm - 网格打包算法

标签 algorithm math fill

给定一个大小为 w x h 的矩形,并要求在 内放置 n 个大小相等的矩形那个较大的矩形,为那些最佳填充原始矩形的较小矩形选择大小 dxdy

主要约束是所有数字必须是整数

我目前的(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];
};

有没有更好的算法?

[注意:这不是家庭作业 - 我正在尝试解决如何在 Canvas 上的矩阵中绘制“n”个项目的问题,但每个项目只能使用完整像素]。

最佳答案

看起来您基本上是在尝试计算 GCD ,您可以使用 Euclidean algorithm 高效地完成此操作.我认为以下方法有效 - 试试吧!

首先,计算 gwn = GCD(w,n) 和 ghn = GCD(h,n)。如果其中任何一个是 n,你就完成了——如果 gwn = n,这意味着每个矩形可以是 w/n x h 像素。否则,只有当 h 能被 n/gwn 整除或 w 能被 n/ghn 整除时,你才能拟合矩形。

关于algorithm - 网格打包算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10553880/

相关文章:

algorithm - 事件参与者的个性化时间表

algorithm - 一般来说,恢复下载是如何工作的?

c++ - 我的交集检查算法有什么问题?

math - float 学有问题吗?

jquery - 通过使用 JQuery 单击图像(标题)来填写输入字段

Java - 最简单的部首形式

algorithm - 两个连通图的并集的属性(如果它们的交集不连通)

javascript - 插入 3d 颜色 Three.js

matlab - 两个时间序列图和它们之间的阴影......MATLAB

html - css h1 字体大小与宽度一样大