Skip to content

Instantly share code, notes, and snippets.

@SalatielSauer
Created January 3, 2022 14:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SalatielSauer/dc0aa7eecec0d092f81a2f4fb2dc9ac5 to your computer and use it in GitHub Desktop.
Save SalatielSauer/dc0aa7eecec0d092f81a2f4fb2dc9ac5 to your computer and use it in GitHub Desktop.
JavaScript function to get the most rectangular image dimension that fits a certain number of pixels with the least (or no) addition of extra pixels.
function pixelsIntoRect(n, k){
var max = ~~Math.sqrt(n);
return Array.from({length: max}, (_, i, a) => [n%(max-i), max-i])
.sort((a, b) => a[0] - b[0])
.slice(0, k)
.map(t => [Math.ceil(n/t[1]), t[1], (Math.ceil(n/t[1])*t[1])-n])
.filter(a => Math.round(a[1]/a[0]) == 1)
.sort((a, b) => a[2] - b[2])
}
pixelsIntoRect(262144)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment