Adobe, MAKE SOME NOISE

Modulo Grids

August 1st, 2009

Here's a quick optimization for people making grids of things. The traditional method is a pair of loops, nested to make rows and columns:

  1. const ROWS:int = 30;
  2. const COLUMNS:int = 88;
  3.  
  4. for(var row:int = 0; row < ROWS; row++){
  5. for(var column:int = 0; column < COLUMNS; column++){
  6. var s:Shape = new Shape();
  7. s.x = column * 5;
  8. s.y = row * 5;
  9.  
  10. s.graphics.beginFill(0x666666);
  11. s.graphics.drawRect(0, 0, 4, 4);
  12. addChild(s);
  13. }
  14. }

This can be simplified and sped up by taking advantage of the relationship between division and modulus to generate the row and column dynamically:

  1. const ROWS:int = 30;
  2. const COLUMNS:int = 88;
  3. const ITEMS:int = ROWS * COLUMNS;
  4.  
  5. for(var i:int = 0; i < ITEMS; i++){
  6. var s:Shape = new Shape();
  7. s.x = int(i / ROWS) * 5; // this is the same as Math.floor(i / ROWS), just faster
  8. s.y = (i % ROWS) * 5;
  9.  
  10. s.graphics.beginFill(0x666666);
  11. s.graphics.drawRect(0, 0, 4, 4);
  12. addChild(s);
  13. }

By upgrading to loop-invariants, we can cut the nested for-loop for a nice boost. And, as a bonus, this new code can work with sets that don't end squarely at the end of a column.

4 Responses to “Modulo Grids”

  1. RodeoClown Says:

    Just a headsup – in the RSS feed, this came up as:

    Modulo Grids
    by Rob
    [insert loads of spam ads for drugs here]

  2. Rob Says:

    Appreciate the heads-up RodeoClown – I’m working on it, and sorry for the spam :[

  3. RodeoClown Says:

    Not a problem, just wanted to make sure you were aware of it.

  4. Math Class « Words of Wise-dumb Says:

    [...] Modulo Grids http://www.calypso88.com/?p=453 [...]

Leave a Reply