Skip to content

Instantly share code, notes, and snippets.

@jsocol
Created November 10, 2011 23:38
Show Gist options
  • Select an option

  • Save jsocol/1356638 to your computer and use it in GitHub Desktop.

Select an option

Save jsocol/1356638 to your computer and use it in GitHub Desktop.
Packing rectangles...
/**
* Return an array of paired factors (arrays) of an integer.
*/
function factor(n) {
var fact = [[1, n]],
check = 2,
root = Math.sqrt(n);
while (check <= root) {
if (n % check == 0) {
fact.push([check, n / check]);
}
check++;
}
return fact;
}
/**
* Given a number of rectangles to construct and dimensions
* to fill, return the [width, height] of the "best fit"
* rectangles.
*/
function find_best_size(n, width, height) {
var f = factor(n),
size = [0, height + width];
for (var i = 0; i < f.length; i++) {
// New browsers only, kthx.
var [x, y] = f[i];
var w = width / y,
h = height / x; // Assuming wide screen/rectangles for now.
// Aim for "most square." This could be replaced with a number of
// properties to optimize, like getting close to the original aspect
// ratio or closest to 4:3, etc.
if (Math.abs(w - h) < Math.abs(size[0] - size[1])) {
size[0] = ~~w, size[1] = ~~h;
}
}
return size;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment