Using Modulo

July 31st, 2006 . by polyGeek

Modulo is probably one of the least used operands in programming. If you’ve forgotten it simply gives you the remainder of a division. As an example 13 % 5 = 3. Five goes into 13 twice with 3 left over. 16 % 7 = 2. Seven goes into 16 twice with 2 left over.

Here’s an example of how it came in handy to help me solve a problem.

Here’s what I was trying to do: I had a long series of thumbnail images in a row. At any one time the user can only see a portion of them. Scrolling through moved them a group at a time - meaning the user couldn’t just scroll over one thumbnail at a time. For instance, if the group size is 8 then scrolling will move over 8 thumbnails thus replacing all the visible thumbnails with a new group.

When the user mouses over a thumbnail it enlarges and some text becomes visible - albumName and artistName. The text appears to the side of the thumbnail. That’s where the math comes in. If the thumbnail is to the left of center then the text would appear on the right side of the thumbnail. Visa-versa for the thumbnails that are right of center.

What I know: the groupSize is a runtime constant but can change from instance to instance. On one page we might have small groups of, say, 4 and on another page have groups of 8. The same goes for the number of thumbnails.

Here’s the code:

// determine which side of the image the album/artist text goes on
var groupHalf:Number = ( i % objData.groupSize );
var isTxtRight:Boolean = ( groupHalf < objData.groupSize / 2 ) ? true : false;

As an example: say that we have 26 ( indexed: 0 - 25 ) thumbnails in a group and we display groups of 8. Suppose I’ve scrolled over twice so that the first visible thumbnail is index number 16. As the thumbnails are placed I need to know if the TextField is to the right or left of the thumbnail. So 16 % 8 = 0, 17 % 8 = 1, 18 % 8 = 2, 19 % 8 = 3, and so on. Essentially what I end up with is a new sequence numbered 0 - 7 for the 8 visible thumbnails. I could have gotten the same numbers by multiplying the visibleGroupNumber by the groupSize and subtracting that from the index number. But using modulo is much more elegant, don’t you think?

Now all I have to do is ask if the new index number - groupHalf - is less-than the groupSize / 2. If it is then it must be part of the first half of the group and so the text will go on the right. Otherwise the text will go on the left.