ColdFusion: Counting to a number and repeating

Ok, this is something I’ve done a thousand times before, but last night when I tried to get it working, it took me a few hours to get it right. I’m sure the first comment on this entry will be a comment showing how much of a bonehead I was, but darnit, I had to get this working or give up programming forever. So what’s the problem? Given a set of records, I want to number them from 1 to 5 so that after 5 I go back to 1 again. Or, given 12 records, I want to see: 1,2,3,4,5,1,2,3,4,5,1,2. Simple, right?

So, I began with a simple script that I could use for testing:

<cfset records = 12> <cfset toCount = 5> <cfloop index="x" from="1" to="#records#"> <cfoutput> Record: #x#<br/> <br/> </cfoutput> </cfloop>

Records simply represent how many iterations I'll be simulating and "toCount" represents the number I'll be counting "up" to and repeating. I then thought about the problem and came up with a formula I wrote out like this:

Take your current number, and subtract from that the whole number of sets (sets being what you are counting up).

So given 12, for example, I have 2 whole sets of 5, for a value of 10. 12-10 is 2. So here is my first take at this:

<cfset records = 12> <cfset toCount = 5> <cfloop index="x" from="1" to="#records#"> <cfset answer = x - (toCount * (x \ toCount))> <cfoutput> Record: #x#<br/> Answer: <b>#answer#</b><br/> <br/> </cfoutput> </cfloop>

And the result:

What the hey? Every time I hit a multiple of 5 I end up with 0. Ok, that makes sense I guess. So what can I do? Just reduce my current row by one. Yeah, that's it:

<cfset records = 12> <cfset toCount = 5> <cfloop index="x" from="1" to="#records#"> <cfset answer = x - (toCount * ((x-1) \ toCount))> <cfoutput> Record: #x#<br/> Answer: <b>#answer#</b><br/> <br/> </cfoutput> </cfloop>

And the result...

So - please - someone tell me there is a much simpler way of doing this?

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate. He focuses on JavaScript, serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support.

Lafayette, LA https://www.raymondcamden.com

Comments