Search code examples
c#arrayspositionoffset

Position in arrays (offset) c#


I have a problem that i can't solve efficiently. What I need to do is : I have a start postion in array(in my case it is list) and I also have an offset. The offset of type int.: enter image description here

When the offset is > 0 I have this to calculate the new position :

        if (currentPosition + offset < lenght)
        {
            return currentPosition + offset;
        }
        return (currentPosition + offset)%lenght;

The problem is when the offset < 0 :

        for (int i = 0; i < offset * -1; i++)
        {
            currentPosition -= 1;
            if (currentPosition == -1)
            {
                currentPosition = lenght - 1;
            }
        }
        return currentPosition;

But this solution is really slow. Do you guys have an idea. Thank you in advance.


Solution

  • I've come up with this function, hope it helps (added in-code comments for clarity):

    private int CalcNewPosition(int[] arr, int position, int offset)
    {
        if (position < 0 || position >= arr.Length)
            throw new ArgumentOutOfRangeException("position");
    
        // Calculate correct offset that is within bounds of array
        // by using modulus of offset divided by array length.
        var offsetOk = offset % arr.Length;
    
        // If offset is negative, calculate how many steps to
        // move forward instead of backwards.
        if (offsetOk < 0)
        {
            offsetOk = arr.Length + offsetOk;
        }
    
        // Calculate new offset
        var result = position + offsetOk;
    
        // If offset is greater or equal than length of array
        // set it to number of elements from beginning by
        // calculating the difference between length and new offset
        if (result >= arr.Length)
        {
            result = result - arr.Length;
        }
    
        return result;
    }
    

    I've tried it with this calls and they all worked (I hope) correctly:

    var pos1 = CalcNewPosition(arr, 3, 2);
    var pos2 = CalcNewPosition(arr, 3, -1);
    var pos3 = CalcNewPosition(arr, 3, -56);
    

    Hope it helps.