首页 > 解决方案 > 循环结果不正确

问题描述

第一个数组是随机填充的,它的长度是从控制台设置的。我有一个数组,我需要在其中编写一个重复数字的子数组和重复数字的数量。例如{3 3 3 3 3 4},3 3 3 3 是重复的数字,4 是它们的数字。

问题是如果数组末尾有重复的数字,循环不会输出它们,如果我进入调试模式,我可以看到并非所有数字都被写入。可能是什么问题呢?

for (int i = 1; i < array.Length; i++)
{
    if (array[i - 1] == array[i])
    {
        if((i + 1) != array.Length)
        {
            duplicateCount++;
            addArray = array[i - 1];
            duplicate += addArray + " ";                        
        }
        else
        {
            duplicateCount++;
            lastElement = array[i - 1];
            duplicate += lastElement;
        }                 
    }
    else
    {                    
        if (duplicateCount != 1)
        {
            addPrevious = array[i - 1];
            duplicate += addPrevious + " ";
            duplicateArrays.Add(duplicate + duplicateCount);
            duplicate = "";
            duplicateCount = 1;
        }
        else
        {
            duplicateCount = 1;
        }
    }
}

duplicateArrays.Add(duplicate + duplicateCount);      

标签: c#arrayslistloops

解决方案


虽然 Antidisestablishmentarianism 代码是最短的代码,但它使用 ' ^ ',它是C# 8.0中引入的end 运算符的索引。我对此并不在意,但这是一个值得了解的区别。在旧版本中编译相同的代码会产生编译时异常。我将给出一个很长但对初学者友好的代码,如果你读两遍,它就很容易解释了。

static void Main(string[] args)
{
    int[] RandomArray = new int[] { 1, 2, 2, 3, 4, 4, 3, 1, 5, 2, 9, 8, 9, 8, 8, 5, 3, 4, 1 };
    int RandomArrayLength = RandomArray.Length;
    List<int[]> SubArrayList = new List<int[]>();
    List<int> visited = new List<int>();
    for (int i = 0; i < RandomArrayLength; i++)
    {
        int elem = RandomArray[i];
        if (!visited.Contains(elem))
        {
            visited.Add(elem);
            List<int> templist = new List<int>();
            for (int j = 0; j < RandomArrayLength; j++)
            {
                if (elem == RandomArray[j])
                {
                    templist.Add(elem);
                }
            }
            if (templist.Count > 1) //You can remove this condition if you want to include all the elements
            {
                int elemCount = templist.Count;
                List<int> sublist = new List<int>();
                sublist.AddRange(templist);
                sublist.Add(elemCount);
                SubArrayList.Add(sublist.ToArray());
            }
        }
        else
        {
            continue;
        }
    }
    int SubArrayListCount = SubArrayList.Count;
    for (int i = 0; i < SubArrayListCount; i++)
    {
        int[] SubArr = SubArrList[i];
        int SubArrCount = SubArr.Length;
        for (int j = 0; j < SubArrCount; j++)
        {
            Console.Write(SubArr[j].ToString() + " ");
        }
        Console.WriteLine();
    }
}

输出:


推荐阅读