function pick(tiles, grid_width, grid_height)
{
var max_area = ~~(grid_width * grid_height / tiles);
for (var area = max_area; area > 0; area--)
{
var result = [grid_width * grid_height - area * tiles];
divisors_do(area,
function (tile_width)
{
var tile_height = area / tile_width;
if (tile_width > grid_width) return true;
if (tile_height > grid_height) return true;
var count_horizontal = ~~(grid_width / tile_width);
var count_vertical = ~~(grid_height / tile_height);
if (count_horizontal * count_vertical < tiles) return true;
result.push([
tile_width, tile_height,
count_horizontal, count_vertical
]);
});
if (result.length > 1) return result;
}
return null;
}
function divisors_do(x, f)
{
var history = [1];
if (f(1) === false) return false;
// for each prime factor
return prime_factors_do(x,
function(prime, primePower)
{
var len = history.length;
for (var iHistory = 0; iHistory < len; iHistory++)
{
var divisor = history[iHistory];
for (var power = 1; power <= primePower; power++)
{
divisor *= prime;
history.push(divisor);
if (f(divisor) === false) return false;
}
}
return true;
});
}
function prime_factors_do(x, f)
{
for (var test = 2; test*test <= x; test++)
{
var power = 0;
while ((x % test) == 0)
{
power++;
x /= test;
}
// If we found a prime factor, report it, and
// abort if `f` returns false.
if (power > 0 && f(test, power) === false)
return false;
}
if (x > 1) return f(x,1);
return true;
}
例子:
> pack(5, 12, 8);
[16, [2, 8, 6, 1], [4, 4, 3, 2]]
> pack(47,1024,768);
[16384, [64, 256, 16, 3], [128, 128, 8, 6], [256, 64, 4, 12], [512, 32, 2, 24]]
第一个示例产生两个等效结果:
- 2x8 块,每排 6 块
- 4x4 瓷砖,每排 3 块
在每种情况下,都有一个插槽未使用,总共有 16 个单元未使用。
### ### ### ### ### . . ####### ####### #######
### ### ### ### ### ####### ####### #######
### ### ### ### ### . . ####### ####### #######
### ### ### ### ### ####### ####### #######
### ### ### ### ### . . ####### ####### #######
### ### ### ### ### ####### ####### #######
### ### ### ### ### . . ####### ####### #######
### ### ### ### ###
### ### ### ### ### . . ####### ####### . . .
### ### ### ### ### ####### #######
### ### ### ### ### . . ####### ####### . . .
### ### ### ### ### ####### #######
### ### ### ### ### . . ####### ####### . . .
### ### ### ### ### ####### #######
### ### ### ### ### . . ####### ####### . . .