title: Algorithm to fill large rectangle with smaller rectangles starting from center
body: <p>I have various sizes of rectangles, and I am trying to fit them into a larger rectangle starting from the center. Below you will find an animation I created to visually describe what needs to take place.</p>
  
  <p>I have been struggling to come up with a way to model this behavior. Does anything exist that is similar to this? I just need to be pointed in the right direction.</p>
  
  <p><img src="https://i.stack.imgur.com/TnCmF.gif" alt="enter image description here"></p>
  
  <p>The following is a very rough explanation:</p>
  
  <p><strong>Initialize</strong></p>
  
  <ul>
  <li>Start with <code>n</code> rectangles</li>
  <li>Order by density (they are really 3d cubes <em>bird's eye view</em>)</li>
  <li>Place first rectangle at center</li>
  </ul>
  
  <p><strong>Remaining rectangles (fit as many as I can)</strong>
  try to group highest density in the center and move outward</p>
  
  <pre><code>Dimensions = { width: 400, height: 300 }
  Boundries = {
    WEST = 0,
    EAST = Dimensions.width,
    NORTH = 0,
    SOUTH = Dimensions.height
  }
  
  // each rectangle has width, height, and other information
  rectArr = Array of {width:60, height:40}
  
  root = { x:EAST/2, y:SOUTH/2 }
  
  foreach rect in rectArr {
    // I will always traverse from the root and try to go left and right. If I cannot, I move up and try the same thing. I then move down. The problem is if there are 5 or more rows. I will be starting from the root and going up, then down, then up-up, then down. It's like I have two parallel trees.
  
    // Try to branch left or right
    if rect.width &lt;= (Boundries.EAST - ('rightmost rectangle'.x + 'rightmost rectangle'.width/2)) branch-right
    if rect.width &lt;= (('leftmost rectangle'.x + 'leftmost rectangle'.width/2) - Boundries.WEST) branch-left
    // Try to branch up or down
    if rect.height &lt;= ((root.x + root.height/2) - Boundries.NORTH) branch-up
    if rect.height &lt;= (Boundries.SOUTH - (root.x + root.height/2)) branch-down
  }
  </code></pre>