title: Create an optimal grid based on n-items, total area, and H:W ratio
body: <p>I'm creating an application that takes a number of equally sized rectangles and positions them in a grid on the screen. I have most of the logic complete for resizing and centering a rectangle within a cell but I'm having trouble with the actual portion that defines the grid the rectangles must conform to.</p>
  
  <p>Ideally, in the end I'd have a function like this (pseudo-code):</p>
  
  <pre><code>
  function getGridDimensions (rect surface, int numItems, float hwRatio) {
      // do something to determine grid-height and grid-width
      return gridDimensions;
  }
  </code></pre>
  
  <p>My original stab at this involved something like this:</p>
  
  <pre><code>
  gridHeight = surface.width / sqrt(numItems);
  gridWidth = surface.height / sqrt(numItems);
  </code></pre>
  
  <p>This would work nicely if my items were all perfect squares, but since they're rectangles there is a lot of unused white space within each cell.</p>
  
  <p>Any thoughts or terms to Google that could point me in the right direction?</p>