Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

algorithm fun



  • Hi all -

    Imagine an array of n items. Given an index v, your task is to "normalize" v so that 0 <= v < n. Two catches:

    1. When the indices extend beyond 0-9, they don't merely repeat; they "mirror." So, if n = 3,
    v  v'
    0 0
    1 1
    2 2
    3 2
    4 1
    5 0
    
    1. must work for negative values of v.

    This didn't seem that complicated at first glance, but I had a heck of a time with it. My solution works, but I'm wondering whether any of you math wizards can simplify it. Here's my solution:

    int getReal(int v, int n) {
        int x;
        int y;
        int z;
    
        x = abs(v);
    
        y = x % (2*n);
    
        if (y >= n) {
            z = n - (x % n) - 1;
        } else {
            z = x % n;
        }
    
        printf("%3d %3d\n", v, z);
    
        return z;
    }
    

    Thanks...


Log in to reply