Clean, efficient algorithm for wrapping integers in C++

后端 未结 14 2035
慢半拍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 09:54

    Personally I've found solutions to these types of functions to be cleaner if range is exclusive and divisor is restricted to positive values.

    int ifloordiv(int x, int y)
    {
        if (x > 0)
            return x / y;
        if (x < 0)
            return (x + 1) / y - 1;
        return 0
    }
    
    int iwrap(int x, int y)
    {   return x - y * ifloordiv(x, y);
    }
    

    Integrated.

    int iwrap(int x, int y)
    {
        if (x > 0)
            return x % y;
        if (x < 0)
            return (x + 1) % y + y - 1;
        return 0;
    }
    

    Same family. Why not?

    int ireflect(int x, int y)
    {
        int z = iwrap(x, y*2);
        if (z < y)
            return z;
        return y*2-1 - z;
    }
    
    int ibandy(int x, int y)
    {
        if (y != 1)
            return ireflect(abs(x + x / (y - 1)), y);
        return 0;
    }
    

    Ranged functionality can be implemented for all functions with,

    // output is in the range [min, max).
    int func2(int x, int min, int max)
    {
        // increment max for inclusive behavior.
        assert(min < max);
        return func(x - min, max - min) + min;
    }
    

提交回复
热议问题