当数组计数不偶数时,继续接收“ System.ArgumentException”

时间:2019-05-22 15:56:57

标签: c# arrays list

我一直收到错误消息:

  

数组的偏移量和长度超出范围,或者计数大于从索引到源集合末尾的元素数量

当数组元素的数量不等于directions.RemoveRange(i, 2);

public static string[] way(String[] arr)
{
    int[] secondaryArr = new int[arr.Length];

    for (int j = 0; j < arr.Length; j++)
    {
        switch (arr[j])
        {
            case "NORTH":
                secondaryArr[j] = 1;
                break;
            case "SOUTH":
                secondaryArr[j] = -1;
                break;
            case "WEST":
                secondaryArr[j] = 2;
                break;
            case "EAST":
                secondaryArr[j] = -2;
                break;
        }
    }

    var directions = arr.ToList();

    for (int i = 0; i < directions.Count / 2; i++)
    {
        for (int j = 0; j < secondaryArr.Length - 1; j++)
        {
            if (secondaryArr[j] + secondaryArr[j + 1] == 0)
            {
                directions.RemoveRange(i, 2);
                i = 0;
                j = 0;
            }
        }
    }

    arr = directions.ToArray();
    return arr;
}

当路线不合理时,我需要减少路线。例如,当我收到诸如[NORTH],[SOUTH],[WEST]之类的输入时,应将其简化为:[WEST],因为转到NORTHSOUTH是不合理的。问题是我无法对数组进行排序。

0 个答案:

没有答案