c# - 循环结果不正确
问题描述
第一个数组是随机填充的,它的长度是从控制台设置的。我有一个数组,我需要在其中编写一个重复数字的子数组和重复数字的数量。例如{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);
解决方案
虽然 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();
}
}
推荐阅读
- html - CSS 样式表在控制台上显示为空白
- python - Numpy计算数组中的项目并存储在字典中
- scala - 在 spark 中自加入并在 spark Scala 中应用多个过滤条件
- sql - SQL - 一个列表中有多少数字在另一个列表中
- javascript - 获取选项卡/浏览器中不活动的持续时间
- node.js - CORS 阻止我将图像/文件发送到我的后端
- elasticsearch - 从弹性搜索索引读取时错误的日期格式
- python - 根据断点数组创建 bin
- python - 获取列表中的单词并在文本文件中搜索它们并计算每个单词的数量
- javascript - 如何使用 jsPDF 中的 addHTML-plugin?(不能通过脚本标签导入)