Clean, efficient algorithm for wrapping integers in C++

后端 未结 14 2019
慢半拍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

    I've faced this problem as well. This is my solution.

    template <> int mod(const int &x, const int &y) {
        return x % y;
    }
    template <class T> T mod(const T &x, const T &y) {
        return ::fmod((T)x, (T)y);
    }
    template <class T> T wrap(const T &x, const T &max, const T &min = 0) {
        if(max < min)
            return x;
        if(x > max)
            return min + mod(x - min, max - min + 1);
        if(x < min)
            return max - mod(min - x, max - min + 1);
        return x;
    }
    

    I don't know if it's good, but I'd thought I'd share since I got directed here when doing a Google search on this problem and found the above solutions lacking to my needs. =)

    0 讨论(0)
  • 2020-12-13 10:14

    I would suggest this solution:

    int Wrap(int const kX, int const kLowerBound, int const kUpperBound)
    {
        int d = kUpperBound - kLowerBound + 1;
        return kLowerBound + (kX >= 0 ? kX % d : -kX % d ? d - (-kX % d) : 0);
    }
    

    The if-then-else logic of the ?: operator makes sure that both operands of % are nonnegative.

    0 讨论(0)
提交回复
热议问题