Actionscript: Outputting a grid using only one for-loop
Sometime this winter a friend of mine (Knut Urdalen) introduced me to a part of mathematics called modular arithmetic. Now that is a nifty little thing.
In modular arithmetic, or modulus if you like, numbers reset themselves when reaching a given limit. Modulus is also known as “clock arithmetic”, and the clock is a very good example for explaining modulus.
A 12 hour clock has a limit of 12, making the hours reset at 12 o’clock. So instead of becoming 13, it simply jumps back to 1. The same thing happens with a 24 hour clock, but at 24 hours instead of 12. This is as simple as I would’ve explained it, but Wolfram has a more in-depth article with links to further reading. I’m sure Google has even more.
In ActionScript you can use modulus like this: x = y % z. Which reads like “x is y modulus to z”.
Following the example of the clock we would have to do a modulus of 12 on the total numbers of hours since the beginning of time to get the current time. Why? Ever since we started keeping track of time the numbers of hours have kept increasing. Time never stops. So instead of saying “oh, the time is 87654826253745 hours”, we do a modulus of 12 on 87654826253745 and get 7. And by looking out of the window we can tell if it is morning or evening.
Modulus can however not be used to count the number of turns the hour hand has turned at 87654826253745 o’clock. It only knows when it has reached the limit, not how many times it has turned.
So, as you probably have guessed already modulus is a drop dead simple way of outputting grids. And this is how I would’ve made a grid of images:
private _max:Number = 20; // Total number of items private _rows:Number = 5; // Items per row private _width:Number = 100; private _height:Number = 100; private function createGrid():void { var ix:Number = 0; for(var i:int=0; i<_max; i++) // Iterate through all items { var col:Number = i % _rows; col==0 ? ++ix : void; x = ix * _width; y = col * _height; } }
Let’s look at each of the lines;
01 : define max number of items in the grid
02 : define max number of items in each row
03 & 04 : width and height of each of the items
08 : x position of row <em>n</em> (increases for each new row)
09 : loop through all items
11 : col is ‘current item’ modulus to ‘items per row’
12 : if col has reset, increase ix by one. Here we jump to the next column
13 : place item at x position ‘ix * _width’
14 : place item at y position ‘col * _height’
And that’s about it. Simple, right?
If anyone of a more mathematical kind of person discovers something wrong, or would’ve explained modulus in a better way, do arrest me. I’m still learning.