I have a fixed size 2D space that I would like to fill with an arbitrary number of equal sized squares. I’d like an algorithm that determines the exact size (length of one side) that these squares should be in order to fit perfectly into the given space.
Share
Notice that there must be an integer number of squares which fill the width and height. Therefore, the aspect ratio must be a rational number.
Input:
width(float or int),height(float or int)Algorithm:
If the width/height is a rational number, your answer is merely any multiple of the aspect ratio! (e.g. if your aspect ratio was 4/3, you could fill it with 4×3 squares of length
width/4=height/3, or 8×6 squares of half that size, or 12×9 squares of a third that size…) If it is not a rational number, your task is impossible.You convert a fraction to lowest terms by factoring the numerator and denominator, and removing all duplicate factor pairs; this is equivalent to just using the greatest common divisor algorithm
GCD(numer,denom), and dividing both numerator and denominator by that.Here is an example implementation in python3:
e.g.
You can tune the optional parameter
maxVerticalSquaresto give yourself more robustness versus floating-point imprecision (but the downside is the operation may fail), or to avoid a larger number of vertical squares (e.g. if this is architecture code and you are tiling a floor); depending on the range of numbers you are working with, a default value ofmaxVerticalSquares=500might be reasonable or something (possibly not even including the exception code).Once you have this, and a range of desired square lengths
(minLength, maxLength), you just multiply:If
shrinkFactoris now2for example, the new output value in the example would be((9*2,47*2), 0.25/2).