Public
Edited
Sep 4, 2023
Importers
3 stars
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
/**
* Computes squares that can be fitted with a rectangle of
* given width and height.
*
* @param {number} w Width of the rectangle
* @param {number} h Height of the rectangle
* @param {number} n Approximate number of squares to fit
* @return {Object} {side, rows, cols, count}
*/
function squaresInRectangle(w, h, n, roundDownSide = false) {
let sx, sy;

const px = Math.ceil(Math.sqrt((n * w) / h));

if (Math.floor((px * h) / w) * px < n) {
sx = h / Math.ceil((px * h) / w);
} else {
sx = w / px;
}

const py = Math.ceil(Math.sqrt((n * h) / w));

if (Math.floor((py * w) / h) * py < n) {
sy = w / Math.ceil((w * py) / h);
} else {
sy = h / py;
}

let side = Math.max(sx, sy);

if (roundDownSide) {
side = Math.floor(side);
}
const rows = Math.floor(h / side);
const cols = Math.floor(w / side);
const count = rows * cols;

return {
side,
rows,
cols,
count
};
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more