Created
June 10, 2021 18:18
-
-
Save kyleshevlin/90aa115938d4c78788ef321f3a50804a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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