Creating Repeated Sequences With The Modulus (MOD) Operator

Posted August 10, 2011 at 9:49 AM by Ben Nadel

Tags: ColdFusion

This almost doesn't warrant its own post; but, it seems to be one of those small factoids that I can't keep in my head without writing it down. And so, a quick post to demonstrate creating repeated sequences with the modulus operator (MOD or %). To be fair, the modulus operator already creates repeated sequences; but, those sequences end with a zero. This is perfect for when you only care about one number in a particular sequence; but, when you want to deal with a sequence as a set of numbers, typically, you want your sequence to start at 1 and proceed to N.

In order to end your sequence on "N", you have to add some math to your modulus calculation. But, before we look at that, let's take a look at a simple modulus loop:

  • <!---
  • Loop to 15 using a modulus of 3 to get a result
  • at each index.
  • --->
  • <cfloop
  • index="i"
  • from="1"
  • to="15"
  • step="1">
  •  
  • #i# % 3 = #(i % 3)#<br />
  •  
  • </cfloop>

Here, we are looping from 1 to 15 and outputting the mod-3 for each index. When we run this code, we get the following output:

1 % 3 = 1
2 % 3 = 2
3 % 3 = 0
4 % 3 = 1
5 % 3 = 2
6 % 3 = 0
7 % 3 = 1
8 % 3 = 2
9 % 3 = 0
10 % 3 = 1
11 % 3 = 2
12 % 3 = 0
13 % 3 = 1
14 % 3 = 2
15 % 3 = 0

As you can see, this creates the repeated sequence, {1,2,0}. Like I said, standard modulus sequences end with zero. This is great if you want to determine which index you are at (1 == first, 0 == last); but, if you wanted to get the index within the repeated sequence, your logic gets a bit more tricky.

To create a repeated sequence that ends in N rather than zero, we have to add some more math to the mix:

  • <!---
  • Now, loop to 15 using a modulus of 3. However, this time,
  • rather than repeating 1,2,0, we want to repeat 1,2,3. To do
  • this, we have to use a slightly different formula:
  •  
  • ((n - 1) % 3) + 1
  • --->
  • <cfloop
  • index="i"
  • from="1"
  • to="15"
  • step="1">
  •  
  • ((#i# - 1) % 3) + 1 = #(((i - 1) % 3) + 1)#<br />
  •  
  • </cfloop>

This time, we are subtracting one from the index and then adding one to the result. When we run this code, we get the following output:

((1 - 1) % 3) + 1 = 1
((2 - 1) % 3) + 1 = 2
((3 - 1) % 3) + 1 = 3
((4 - 1) % 3) + 1 = 1
((5 - 1) % 3) + 1 = 2
((6 - 1) % 3) + 1 = 3
((7 - 1) % 3) + 1 = 1
((8 - 1) % 3) + 1 = 2
((9 - 1) % 3) + 1 = 3
((10 - 1) % 3) + 1 = 1
((11 - 1) % 3) + 1 = 2
((12 - 1) % 3) + 1 = 3
((13 - 1) % 3) + 1 = 1
((14 - 1) % 3) + 1 = 2
((15 - 1) % 3) + 1 = 3

As you can see, this time, we created the repeated sequence, {1,2,3}. With the extra math, we were able to end on N (3 in our case) rather than zero.

And, of course, we could abstract this concept out into its own function:

  • <cffunction
  • name="modSequence"
  • access="public"
  • returntype="numeric"
  • output="false"
  • hint="I return the modulus result of the given value into the given sequence such that the resultant sequence goes from 1 to N (rather than zero).">
  •  
  • <!--- Define arguments. --->
  • <cfargument
  • name="index"
  • type="numeric"
  • required="true"
  • hint="I am the index that we will fit into the given sequence."
  • />
  •  
  • <cfargument
  • name="sequence"
  • type="numeric"
  • required="true"
  • hint="I am sequence (max value) into which we will be fitting the given index."
  • />
  •  
  • <cfreturn (((arguments.index - 1) % arguments.sequence) + 1) />
  • </cffunction>
  •  
  •  
  • <!--- loop to 15, repeating 1,2,3. --->
  • <cfloop
  • index="i"
  • from="1"
  • to="15"
  • step="1">
  •  
  • modSequence( #i#, 3 ) = #modSequence( i, 3 )#<br />
  •  
  • </cfloop>

Here, we're simply encapsulating the details behind a function invocation. When we run the above code we get the following page output:

modSequence( 1, 3 ) = 1
modSequence( 2, 3 ) = 2
modSequence( 3, 3 ) = 3
modSequence( 4, 3 ) = 1
modSequence( 5, 3 ) = 2
modSequence( 6, 3 ) = 3
modSequence( 7, 3 ) = 1
modSequence( 8, 3 ) = 2
modSequence( 9, 3 ) = 3
modSequence( 10, 3 ) = 1
modSequence( 11, 3 ) = 2
modSequence( 12, 3 ) = 3
modSequence( 13, 3 ) = 1
modSequence( 14, 3 ) = 2
modSequence( 15, 3 ) = 3

The modulus operator is pretty awesome, no doubt. Hopefully, I'll now be able to remember how to use it to create a more "standard" repeated sequence. And if I can't, at least I know where to look.




Reader Comments

Aug 10, 2011 at 11:10 AM // reply »
347 Comments

When I first started programming, I thought the MOD operator was the coolest, most awesome and interesting thing. I still love it to this day. Thanks for writing about it. You get extra brownie points, as well, for adding extra math. :-)


Aug 10, 2011 at 1:35 PM // reply »
10,743 Comments

@Anna,

Yeah, the mod operator is totally awesome :) It's one of my favorite operators (which may very well be the geekiest thing I say all day).


Aug 10, 2011 at 3:13 PM // reply »
347 Comments

@Ben,

haha...you can be geeky, that's ok. I am geeky all day, every day, probably, but it's gotten so bad with me, that I don't even really notice it anymore, and don't recognize it when I am.


Aug 10, 2011 at 7:43 PM // reply »
260 Comments

@Ben,

If you cfloop from -6 to 6, instead of from 1 to 15, you'll see that % is actually a remainder operator, not a true modulo. In a true modulo, -5 % 3 would 1, not -2.

It can make a difference if you're trying to generate a random number within a range. Say you want to generate a random number in the range of 0 to 59, to represent the number of seconds to wait before doing something. Ordinarily, % 60 does that quite nicely. But if the first operand accidentally goes negative somehow, you instead get a number in the range of -59 to 0.

Just something to watch out for.


Aug 10, 2011 at 8:02 PM // reply »
260 Comments

This might be a bit more visual. Switching to code for its monofont.

  • Remainder versus true modulo:
  •  
  • i i \ 3 i % 3 true i mod 3
  •  
  • -6 -2 0 0
  • -5 -1 -2 1
  • -4 -1 -1 2
  • -3 -1 0 0
  • -2 0 -2 1
  • -1 0 -1 2
  • 0 0 0 0
  • 1 0 1 1
  • 2 0 2 2
  • 3 1 0 0
  • 4 1 1 1
  • 5 1 2 2
  • 6 2 0 0

You can take integer quotient times divisor and add in the remainder to get the dividend, on either side of 0.

You can't do that with true modulo.


Aug 10, 2011 at 8:03 PM // reply »
260 Comments

Aw, shucks. I wish you would allow pre in addition to code.


Aug 15, 2011 at 11:41 AM // reply »
347 Comments

@Ben, I forgot to mention that I like the other operators, too. It's just that by the time I got to the mod operator, I had used the others so much, I had just grown kind of tired of them. They were kind of like old news at that point. But I still like them. Just think the mod is super-cool. (and can be helpful for a lot of solutions to different problems you can't really solve easily in other ways).


Aug 18, 2011 at 9:41 AM // reply »
154 Comments

We use MOD to place things in row, three columns wide. Thus, if there are eight items, the output ends up looking like:
1 2 3
4 5 6
7 8
is that what prompted this post, Ben?


Oct 29, 2011 at 10:02 PM // reply »
10,743 Comments

@WebManWalking,

It's funny you mention that - I almost never think about numbers in the negative. I know that sounds odd; but, I can't even remember the last time that I really had to work with negative numbers. ... I am sure that is a ridiculous thought - I am sure I use them all the time :)

@Randall,

That's the kind of situation where I really started to use MOD for the first time on a regular basis. When I was using Table tags to lay things out, especially, I remember I used to use the MOD operator to determine where I should add the closing / opening TR tags.


Post A Comment

Comment Etiquette: Please do not post spam. Please keep the comments on-topic. Please do not post unrelated questions or large chunks of code. And, above all, please be nice to each other - we're trying to have a good conversation here.

Please review the following issues:

Author Name:


Author Email:

Author Website:

Comment:

Supported HTML tags for formatting: <strong>bold</strong>   <em>italic</em>   <code>code</code>







  • Help Wanted - Find Your Next ColdFusion Job
InVision App - Prototyping Made Beautiful With Prototyping Tools Ben Nadel's Company - Epicenter Consulting Recent Blog Comments
May 21, 2012 at 1:58 AM
Updated: Converting A ColdFusion Query To CSV Using QueryToCSV()
Hi Ben, why do you need to have so many double quotes when adding the field and field name to the row data? ----------------------------------------- <cfset LOCAL.RowData[ LOCAL.ColumnIndex ] = ... read »
AXL
May 21, 2012 at 1:24 AM
URL Rewriting And ColdFusion's WriteToBrowser Image Functionality (CFFileServlet)
@Mounir, Open your lower case URL Rewrite rule and add the following condition. Condition input: {REQUEST_URI} Check if input string: Does Not Match the Pattern Pattern: ^/CFFileServlet/_cf_ca ... read »
May 20, 2012 at 4:28 AM
Understanding The Complex And Circular Relationships Between Objects In JavaScript
@Will Vaughn I tried your javascript example but got this error:- foo.print is not a function ... read »
May 19, 2012 at 5:37 AM
A Graphical Explanation Of Javascript Closures In A jQuery Context
Thanks for this article, but I fear you missed an important point. If variables in the outer context change, these changes affect the inner anonymous functions as well. That means: if you change the ... read »
May 18, 2012 at 3:39 PM
Parsing CSV Data With An Input Stream And A Finite State Machine
Can you use file upload button with this? and read live? or does the file have to already be on the server saved? ... read »
May 18, 2012 at 1:06 AM
VIRGO (Aug. 23-Sept. 22): Dead On The Money!
A friend of mine and I were arguing about astrology and she told me that he believes in astrology. She hasn't provided me with any evidence that the belief makes any sense to me. She she been telling ... read »
May 17, 2012 at 11:32 PM
Using ColdFusion to Handle 404 Errors (Page Not Found) On Development Server
Very easy the configuration. I read a lot pages and I can't find the solution. I open the administrator and change this Administrator/server settings/Error Handlers/Missing Template Handler and p ... read »
May 17, 2012 at 3:13 PM
LOCAL Variables Scope Conflicts With ColdFusion Query of Queries
I never cease to be amazed that almost EVERY random CF issue I come across lands me on your site. Thank you for documenting your findings for the world. ... read »