My mathematical suck it showing =O

Maximilian

Lifer
Feb 8, 2004
12,604
15
81
So im simulating a circular buffer in java using an Array, there's a line of code that prevents the Array from going out of bounds.

Thats this line, size is the size of the Array:
Code:
in = (in + 1) % size;

It took me a while to figure out that's what the "% size" is actually for (i know its modulus i mean why it was there in the first place) and im still not 100% sure on it. Its like (in + 1) modulus size always keeps it in bounds because it just does is my current level of understanding of this :|

I wrote this instead:
Code:
if (in == (size - 1))
        {
            in = 0;
        }

Yeah its longer yeah it takes 4 lines instead of 1 but i find that infinitely easier to understand than the other line, if something then something otherwise ignore it and continue. Is what i wrote significantly worse than the original line?
 

Crusty

Lifer
Sep 30, 2001
12,684
2
81
Modulo division returns the remainder instead of the quotient.

5 % 2 = 1
5 % 1 = 0
5 % 5 = 0
5 % 3 = 2
 

Markbnj

Elite Member <br>Moderator Emeritus
Moderator
Sep 16, 2005
15,682
14
81
www.markbetz.net
First, is this check before the write, or after? It it's before then you want to wrap at size, right? Not size - 1 as shown.

I prefer your code, personally. I've never been a fan of terseness winning over clarity, and in this case by clarity I mean being able to discern the logical requirement that the code is fulfilling from reading it. Whether there is a performance advantage or disadvantage between the two I'll leave for others to discuss, and that discussion is probably relevant in a buffer check like this, but with the optimization abilities of modern compilers I wouldn't expect a big difference.
 

Maximilian

Lifer
Feb 8, 2004
12,604
15
81
Modulo division returns the remainder instead of the quotient.

5 % 2 = 1
5 % 1 = 0
5 % 5 = 0
5 % 3 = 2

Yeah i know what it does im saying that never in a million years would i have considered it could be useful for keeping an array in bounds, even now i know it can be used for that it dosent sit right. In my head it can be used because ive seen it done before, rather than because i understand how its done.

First, is this check before the write, or after? It it's before then you want to wrap at size, right? Not size - 1 as shown.

I prefer your code, personally. I've never been a fan of terseness winning over clarity, and in this case by clarity I mean being able to discern the logical requirement that the code is fulfilling from reading it. Whether there is a performance advantage or disadvantage between the two I'll leave for others to discuss, and that discussion is probably relevant in a buffer check like this, but with the optimization abilities of modern compilers I wouldn't expect a big difference.

This is done after the write, so after an object is put into the array. Yeah it would be at size if it was before the write.

I guess this is why lots of devs work in teams, hopefully someone on the team would be able to help optimize if what i wrote was sucking a bit too much resources :)
 

Markbnj

Elite Member <br>Moderator Emeritus
Moderator
Sep 16, 2005
15,682
14
81
www.markbetz.net
Yeah i know what it does im saying that never in a million years would i have considered it could be useful for keeping an array in bounds, even now i know it can be used for that it dosent sit right.

It's just an expression that can force a value to be within certain limits, so I'm not saying it's an invalid approach. I just feel like the explicit if-test against the array bounds is clearer. It used to be almost a pastime of programmers to try and reduce the number of bytes of instructions required to make something happen, and in those days you saw a lot of this kind of trick. I think the clarity vs. terseness meter has swung pretty much all the way to the other peg these days.
 

dighn

Lifer
Aug 12, 2001
22,820
4
81
to be honest I've seen and used the (i + 1) % n pattern so many time that I find it a lot easier to read than the other one ;) i just equate % n to "wrap around"
 
Last edited:

beginner99

Diamond Member
Jun 2, 2009
5,235
1,611
136
I prefer your code, personally. I've never been a fan of terseness winning over clarity, and in this case by clarity I mean being able to discern the logical requirement that the code is fulfilling from reading it.

Yeah and that's why I'm doubtful purely functional languages will take off besides specific niches. I don't doubt any advantages or whatever but the fact that you can't just read and understand the code makes it even harder if you did not write it yourself. There is a reason procedural stuff was first because it's easy to understand and follow (at least without go to). OOP is a bit harder but it makes sense on a higher level that it easy to understand and following methods calls from object to object or so isn't hard just tedious.
Functional stuff is IMHO on a whole other level. Maybe it's because I'm just not clever enough but for me it is not a natural way of doing things and thinking.
 

Maximilian

Lifer
Feb 8, 2004
12,604
15
81
Okay i get it now.

if x < size (which it should be to begin with) then modulus x will always return x until x == size in which case x will divide by size exactly once and modulus will of course return the remainder as 0 and so we're back to the beginning again!

Took a bit of processing but ive got my head around it now :) I still like my if then solution but ill not be thrown off by a modulus in the future (in this situation anyways).

Whats the difference between java and a functional programming language? Seems like a more complex way to accomplish the same thing, based on my brief skim of the wiki on it.
 

veri745

Golden Member
Oct 11, 2007
1,163
4
81
The modulo arithmetic is useful for generalizing stepping through the array in step of any size.
Code:
index = (index + step) % size;

Your case only works for increments of 1 (which is totally fine if that's all you need it to do).

*edit* The example I gave is frequently used in cryptography, where size and step must be semi-prime.
 
Last edited:

Crusty

Lifer
Sep 30, 2001
12,684
2
81
The modulo arithmetic is useful for generalizing stepping through the array in step of any size.
Code:
index = (index + step) % size;

Your case only works for increments of 1 (which is totally fine if that's all you need it to do).

Just need to change the == to a >= to protect against that.
 

Crusty

Lifer
Sep 30, 2001
12,684
2
81
No, it doesn't, if you're at index 9 of 10, and increment by 3, you should be at index 1, not 0.

Well you didn't say anything about requiring that :p

All you gotta do then is subtract size from in instead of setting it to 0.

The point being that numerically you can make the logic equivalent and then it comes down to what Mark said above... code clarity and speed.
 

veri745

Golden Member
Oct 11, 2007
1,163
4
81
Well you didn't say anything about requiring that :p

All you gotta do then is subtract size from in instead of setting it to 0.

The point being that numerically you can make the logic equivalent and then it comes down to what Mark said above... code clarity and speed.

It was the OP that specified "circular buffer".

Code:
index = index + step;

if (index >= size) {
   index = index - size;
}

You consider that more readable? It's certainly not faster...
 

Crusty

Lifer
Sep 30, 2001
12,684
2
81
It was the OP that specified "circular buffer".

Code:
index = index + step;

if (index >= size) {
   index = index - size;
}

You consider that more readable? It's certainly not faster...

I never took a side and I'm not trying to start a style holy war here.... readability is subjective, if you want to judge me on that, be my guest.
 

veri745

Golden Member
Oct 11, 2007
1,163
4
81
I never took a side and I'm not trying to start a style holy war here.... readability is subjective, if you want to judge me on that, be my guest.

Don't get me wrong, I complete agree with Mark's post, and I'm not trying to be disagreable.

I was just trying to inject the idea that using modulo arithmetic instead of the "increment and check" approach has its place in certain scenario's, and I feel like the generalized case I mentioned is one of them.

There's always several ways to skin a cat.
 

mv2devnull

Golden Member
Apr 13, 2010
1,512
149
106
The modulo arithmetic is useful for generalizing stepping through the array in step of any size.
Code:
index = (index + step) % size;
This expression performs two operations: (1) increment of a counter, and (2) wrap of the counter into allowed range. Both in one non-conditional arithmetic expression. It could be split for one bit of extra clarity:
Code:
index += step; // index = index + step;
index %= size; // index = index % size;
The if-clause version does only the wrapping, so OP did omit to show the increment. Therefore, the "1 vs 4 lines" analysis in OP was formally a case of "apples to oranges".

A more generic check/wrap with a conditional:
Code:
index += step;
while ( size <= index )
  {
    index -= size;
  }
Personally I do prefer arithmetic, but the important thing is to (1) understand, and (2) have the code do the right thing for right reasons.
 
Last edited:

iCyborg

Golden Member
Aug 8, 2008
1,332
56
91
to be honest I've seen and used the (i + 1) % n pattern so many time that I find it a lot easier to read than the other one ;) i just equate % n to "wrap around"
+1

I agree with the general sentiment that clarity is often better than saving a few lines of code, but in this particular case, the construct is so common that I find it easier to understand. It's kind of like saying that "i = i + 1;" is more clear and easier to understand than "++i;", which is true, but no self-respecting programmer would use the former instead of the latter.
 

Markbnj

Elite Member <br>Moderator Emeritus
Moderator
Sep 16, 2005
15,682
14
81
www.markbetz.net
+1

I agree with the general sentiment that clarity is often better than saving a few lines of code, but in this particular case, the construct is so common that I find it easier to understand. It's kind of like saying that "i = i + 1;" is more clear and easier to understand than "++i;", which is true, but no self-respecting programmer would use the former instead of the latter.

At least with i = i + 1 there's no getting tripped up over when the value is taken :). I've seen lots of new C++ people over the years get caught by the difference between pre- and post-fix increment and decrement. But anyway, it's a fair assessment. Once a shortcut becomes the lingua franca there's no real loss of clarity in using it.

One one end of the spectrum you have code that's written as clearly and as straightforwardly as possible. On the other you have examples from the old Obfuscated C contest. How much behavior can you cram into the fewest instructions? It was fun, but good production code lies somewhere a lot closer to the other end of the range.