Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
function createRectFromPortion(portion, areaName) {
const sqrt = Math.sqrt(portion)
const upper = Math.ceil(sqrt)
const lower = Math.floor(sqrt)
const square = upper ** 2
const squareDiff = square - portion
const rect = lower * upper
const rectDiff = rect - portion
const cols = upper
let rows
if (rectDiff <= 0 || squareDiff < rectDiff || squareDiff === rectDiff) {
rows = upper
} else {
rows = lower
}
const result = []
let count = 0
for (let row = 0; row < rows; row++) {
for (let col = 0; col < cols; col++) {
count++
if (!result[row]) {
result[row] = []
}
result[row][col] = count <= portion ? areaName : '.'
}
}
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment