繁体   English   中英

数组中的位置(偏移)C#

[英]Position in arrays (offset) c#

我有一个我无法有效解决的问题。 我需要做的是:我在array中有一个起始位置(在我的情况下是list),并且还有一个偏移量。 int类型的偏移量: 在此处输入图片说明

当偏移量> 0时,我可以用它来计算新位置:

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

问题是偏移量<0时:

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

但是这个解决方案确实很慢。 你们有个主意吗? 先感谢您。

看起来currentPosition是一个整数。 因此,您可以进行计算,如果小于零则进行校正;

currentPosition = (currentPosition + offset) % lenght;
if (currentPosition<0)
    currentPosition += lenght;
return currentPosition;

我想出了这个功能,希望对您有所帮助(为清楚起见添加了代码内注释):

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;
}

我已经通过此调用进行了尝试,它们都正常工作(我希望):

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

希望能帮助到你。

特定

(A)0 <长度&&长度<= int.MaxValue / 3
(B)0 <=位置&&位置<长度
(C)-长度<偏移&&偏移<长度

计算可能是

position = (position + offset + length) % length;

如果(C)不成立,我们可以将其转换为相同的大小写, offset % length ,公式将改为

position = (position + (offset % length) + length) % length;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM