Skip to content

Instantly share code, notes, and snippets.

@kyleshevlin
Created June 10, 2021 18:18
Show Gist options
  • Save kyleshevlin/90aa115938d4c78788ef321f3a50804a to your computer and use it in GitHub Desktop.
Save kyleshevlin/90aa115938d4c78788ef321f3a50804a to your computer and use it in GitHub Desktop.
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