【问题标题】:C#: loop through array of numbers and put consecutive numbers in one array, and all other numbers else in other arrayC#:遍历数字数组并将连续数字放在一个数组中,其他所有数字放在另一个数组中
【发布时间】:2017-12-07 16:54:48
【问题描述】:

我有一个未排序的数字数组。此数组中的大多数数字是连续的(1、2、3、4、5,...),但有时其中的数字高于其他数字。

int highestNumber = int.MinValue;
int secondHighestNumber = int.MinValue;

int[] arr = new int[] { 1, 2, 3, 4, 5, 6, 1207, 7, 8, 9, 1803, 10, 11, , 9000, 9001 };
int counter = 0;

foreach (int number in arr) {
    if (number > highestNumber) {
        secondHighestNumber = highestNumber;
        highestNumber = number;
    }
    else if (number > secondHighestNumber) secondHighestNumber = number;
}

当我运行代码时,它会告诉我 9001 是最大的数字,而 9000 是第二高的数字。但我想改变它,以便我得到一个从 1 到 11 的所有数字的数组,所有连续的数字只有一个差异,第二个数组包含所有更大的数字:1207、1803、9000 和 9001。
9000 和 9001 不应该在第一个数组中,因为这些数字与其余数字之间的差异太大。所以最终的结果应该是这样的:

int[] arr1 = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
int[] arr2 = new int[] { 1207, 1803, 9000, 9001 };

关于这样做的目的的一些背景信息:
Cient 创建文章,每篇文章都有一个文章编号,该编号是通过在“文章”表中查找最高文章编号创建的(例如 20),然后新文章的编号是该编号 + 1(例如 21 );所以每个数字的增量。然而,客户希望有时能够添加文章并输入他想要的文章编号,所以假设他创建的最后一篇文章输入了 7000 作为文章编号。如果他在那之后创建另一篇文章,我必须继续那个递增数字列表。因此,除非客户端再次更改下一篇文章的值,否则下一篇新文章应该有 22 作为文章编号(而不是 7001)。

任何帮助将不胜感激,因为我一直在努力解决这个问题。

【问题讨论】:

  • 排序,然后从头开始。
  • @ThomasWeller 但随后代码将返回 9001 作为最高,9000 作为第二高。
  • arr.Select(i => i+1).Except(arr).Min()
  • 该列表是否从 1 开始?如果 1 不在列表中,是否应该建议 1 作为下一个数字?
  • @Magali 你最后的两个cmets(对Bradley Uffner 和对ThomasWeller)不会加在一起。如果它总是从 1 开始,那么对 { 10, 11, 12, 100, 101, 102, 500, 501, 505 } 的回答将是 1,因为它不在列表中。如果你总是增加最低范围(可能只包括一个数字),那么你不会总是从 1 开始。

标签: c# arrays int increment


【解决方案1】:

我不确定您是否只是想获得下一个您应该使用的号码,或者您想要 2 套。如果你想要这两套,我会这样做:

int[] arr = new int[] { 1, 2, 3, 4, 5, 6, 1207, 7, 8, 9, 1803, 10, 11, , 9000, 9001 };
int counter = 0;
List<int> l1 = new List<int>();
List<int> l2 = new List<int>();

foreach (int number in arr) {
    if(l1.Count==0 || l1[l1.Count-1] == (number -1))
        l1.Add(number);
    else
        l2.Add(number);
}

【讨论】:

    【解决方案2】:
    int[] arr = new int[] { 1, 2, 3, 4, 5, 6, 1207, 7, 8, 9, 1803, 10, 11, 9000, 9001 };
    
    // Sort the array
    Array.Sort(arr);
    
    // Start at the beginning and check if the index matches the actual number.
    // Computer begins at 0, so fix that
    for (int index=0;index<arr.Length; index++)
    {
        if (arr[index] != index+1)
        {
            Console.WriteLine("Next ID is " +(index+1));
            break;
        }
    }
    

    【讨论】:

    • 你可以重新设计你的方法。为每篇文章存储两个编号,即系统生成的编号:1、2、3……和客户分配的编号(如果存在)。使用适合每种情况的任何数字。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-17
    相关资源
    最近更新 更多