【问题标题】:Position in arrays (offset) c#数组中的位置(偏移量)c#
【发布时间】:2016-01-19 20:28:15
【问题描述】:

我有一个无法有效解决的问题。 我需要做的是: 我在数组中有一个起始位置(在我的情况下是列表),我也有一个偏移量。 int 类型的偏移量:

当偏移量 > 0 时,我有这个来计算新位置:

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

问题是当偏移量

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

但是这个解决方案真的很慢。 各位有什么想法吗。 提前谢谢你。

【问题讨论】:

  • 偏移量可以大于+7还是小于-7?另外,这总是 8 元素数组还是长度可以变化?
  • 数组的长度可以变化,偏移量可以大于数组的长度。

标签: c# arrays position offset


【解决方案1】:

看起来currentPosition 是一个整数。所以你可以只做计算,如果它小于零,然后再更正;

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

【讨论】:

    【解决方案2】:

    我想出了这个函数,希望对你有帮助(为了清楚起见,添加了代码中的 cmets):

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

    希望对你有帮助。

    【讨论】:

    • 非常感谢。我在我的代码中做到了,它就像一个魅力。也谢谢你的好解释。
    【解决方案3】:

    给定

    (A) 0 (B) 0 (C) -length

    计算可能是

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

    如果 (C) 不成立,我们可以将其变成与 offset % length 相同的情况,而公式将改为

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

    【讨论】:

    • 极限实际上是 (int.MaxValue + 2) / 3
    猜你喜欢
    • 2013-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-27
    • 2018-03-01
    相关资源
    最近更新 更多