[英]Rotate through a zero based range for positive and negative numbers
Say I have a zero-based range like假设我有一个从零开始的范围,例如
[0, 1, 2, 3, 4]
these are essentially the indexes of an array with size = 5. Is it possible to use a signed integer variable to continuously loop up or down in that range?这些本质上是大小 = 5 的数组的索引。是否可以使用带符号的 integer 变量在该范围内连续向上或向下循环?
By up or down, I mean that the variable is permitted to perform arbitrarily many increment or decrement operations :通过向上或向下,我的意思是允许变量执行任意多个递增或递减操作:
++index;
--index;
So for example decrementing the index should map to following values:因此,例如将索引应该 map 减少到以下值:
index = 2;
while (/*...*/)
{
--index;
index_in_range(index, 5);
}
The function index_in_range(index, 5)
would output: function index_in_range(index, 5)
将 output:
[1, 0, 4, 3, 2, 1, 0, 4, 3, 2, 1, .... and so on]
The positive case is just a modulo operation over the range size, but for the negative I can't figure out how the mapping goes.正面的情况只是对范围大小的模运算,但对于负面的情况,我无法弄清楚映射是如何进行的。
C made a really poor decision for %
to round towards zero, rather than be a straightforward floor, so the math's clunkier than it has to be. C 做出了一个非常糟糕的决定,将%
舍入到零,而不是一个简单的下限,所以数学比它必须的更笨拙。 Basically, though, you want (index % size + size) % size
.不过,基本上,您想要(index % size + size) % size
。 That code starts by chopping off the negative or positive multiples to bring the index into the range (-size, size)
, adds size
to map it into (0,size*2)
, and a final %
to map it into [0,size)
.该代码首先切断负倍数或正倍数以使索引进入范围(-size, size)
,将 map 的size
添加到(0,size*2)
中,最后将 map 的%
添加到[0,size)
。
If size
is not known at compile time, it's likely more performant to replace everything after the first modulus with a conditional: index %= size; if(index < 0) index += size;
如果在编译时不知道size
,则用条件替换第一个模数之后的所有内容可能会更高效: index %= size; if(index < 0) index += size;
index %= size; if(index < 0) index += size;
. .
To increase增加
index = (index+1)%sz;
To decrease减少
index = (index-1+sz)%sz
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.