How could I have the index of an array 'roll over' when incrementing?

前端 未结 4 374
刺人心
刺人心 2020-12-20 19:59

So I have an Array with a length of 4. When I increment it by 1 and the number gets bigger than the length of the array, I\'d like it to rollover.

For example:

相关标签:
4条回答
  • 2020-12-20 20:13

    You can use the modulo operator.

    current_index = (current_index + n) % 4;
    
    0 讨论(0)
  • 2020-12-20 20:15

    Just set it to itself modulo 4 - or rather, the length of the list - after each increment.

    current_index += 2;
    current_index %= textviewlist.length;
    

    or combined:

    current_index = (current_index + 2) % textviewlist.length;
    

    You could also do this:

    current_index += n;
    while (current_index >= textviewlist.length) {
        current_index -= textviewlist.length;
    }
    

    although I'd be surprised if that isn't slower than the modulo operation, especially since your list length is a power of 2.

    Either way, it might be a good idea to encapsulate all this into an increment() function:

    int increment(int old_index, int n) {
        return (old_index + n) % textviewlist.length;
    }
    

    EDIT: ah, I didn't realize you were working in Java. (I think C's modulo operator mimics the mathematical definition on negative numbers) A slight improvement on the solution you found would be

    int increment(int old_index, int n) {
        return (old_index + n + textviewlist.length) % textviewlist.length;
    }
    
    0 讨论(0)
  • 2020-12-20 20:21

    You can use mod as follows:

    current_index = (current_index + i) % 4.
    
    0 讨论(0)
  • 2020-12-20 20:26

    Divide the incremented index modulo the array's length:

    current_index = (current_index + n) % textviewlist.length
    
    0 讨论(0)
提交回复
热议问题