Clean, efficient algorithm for wrapping integers in C++

后端 未结 14 2050
慢半拍i
慢半拍i 2020-12-13 09:21
/**
  * Returns a number between kLowerBound and kUpperBound
  * e.g.: Wrap(-1, 0, 4); // Returns 4
  * e.g.: Wrap(5, 0, 4); // Returns 0      
  */
int Wrap(int con         


        
14条回答
  •  佛祖请我去吃肉
    2020-12-13 10:11

    Please do not overlook this post. :)

    Is this any good?

    int Wrap(N,L,H){
      H=H-L+1; return (N-L+(N

    This works for negative inputs, and all arguments can be negative so long as L is less than H.

    Background... (Note that H here is the reused variable, set to original H-L+1).

    I had been using (N-L)%H+L when incrementing, but unlike in Lua, which I used before starting to learn C a few months back, this would NOT work if I used inputs below the lower bound, never mind negative inputs. (Lua is built in C, but I don't know what it's doing, and it likely wouldn't be fast...)

    I decided to add +(N to make (N-L+(N, as C seems to be defined such that true=1 and false=0. It works well enough for me, and seems to answer the original question neatly. If anyone knows how to do it without the MOD operator % to make it dazzlingly fast, please do it. I don't need speed right now, but some time I will, no doubt.

    EDIT:

    That function fails if N is lower than L by more than H-L+1 but this doesn't:

    int Wrap(N,L,H){
      H-=L; return (N-L+(N

    I think it would break at the negative extreme of the integer range in any system, but should work for most practical situations. It adds an extra multiplication and a division, but is still fairly compact.

    (This edit is just for completion, because I came up with a much better way, in a newer post in this thread.)

    Crow.

提交回复
热议问题