【问题标题】:Checking for consecutive numbers检查连续数字
【发布时间】:2019-07-21 21:25:26
【问题描述】:

我正在尝试实现一种方法来检查C# 中的连续数字。 给定一个n 元素的整数列表,如果数字是连续的,它应该返回真/假。 例如,12345, 45678, 54321 都将是 true。 而435276, 243516, 974264 将是false。

我的代码似乎按预期执行。但它缺少结束元素。

for (int i = 0; i < inputList.Count - 1; i++)
{
    if (inputList[i] < inputList[i + 1])
    {
        Console.WriteLine($"{inputList[i]} is consecutive when compared to {inputList[i + 1]}");
        consecutiveCheck = true;
    }
    else
    {
        Console.WriteLine($"{inputList[i]} is not consecutive when compared to {inputList[i + 1]}");
        consecutiveCheck = false;
        break;
    }
}

【问题讨论】:

  • 这些不是连续的数字,而是递增的数字。
  • 缺少结尾元素是什么意思?对于哪个输入,它会失败以及如何失败?
  • dotnetfiddle.net/wEPqLS 您的代码@Keva161 的具体问题是什么?它似乎工作正常。 But it's missing the end element. 当然,代码只给出两行输出,但这是意料之中的。如果你有三个值,那么你就有两个比较。
  • 当 ContinuousCheck 设置为 false 时,您的代码不能保证将所有元素输出到控制台,因为循环由于 break 语句而终止。

标签: c# algorithm


【解决方案1】:

这是一个简单的方法:

int[] inputList = new [] { 12345, 45678, 54321 };

bool all_increasing = inputList.Zip(inputList.Skip(1), (x0, x1) => x1 > x0).All(x => x);

【讨论】:

    【解决方案2】:

    你的意思是你正在检查它们是否在增加:

    bool inc = true;
    for (int i = 1; i < inputList.Count; i++)
    {
        if (inputList[i] < inputList[i - 1])
        {
           inc=false;
           break;
        }
    }
    
    Console.WriteLine($"List has consecutive numbers: {(inc?"yes":"no")}");
    

    【讨论】:

    • 我的意思是,这并不能解决问题。 (我实际上相信没有问题)(PS。虽然我没有投反对票)
    • 再看问题,没有。
    • @JessedeWit,“给定一个包含 n 个元素的整数列表,它应该返回真/假”...
    • 是的,您的代码可以工作,但 TO 的代码也可以。
    【解决方案3】:

    此代码将起作用:

        private static bool isConsecutive(int[] list)
        {
            switch (list.Length)
            {
                case 0:
                    throw new ArgumentException("Value cannot be an empty collection.", nameof(list));
                case 1:
                    throw new ArgumentException("This collection contains only one element.", nameof(list));
            }
    
            int direction = list[1]-list[0];
    
            for (var index = 0; index < list.Length; index++)
            {
                int nextIndex = index + 1;
    
                if (nextIndex >= list.Length)
                {
                    continue;
                }
    
                int diff = list[nextIndex] - list[index];
    
    
                if (diff != direction)
                {
                    return false;
                }
    
            }
    
            return true;
        }
    

    【讨论】:

    • 这将为 [1,2,1,2,1,2,1,2,1,2,1,2] 返回 true,对于 [1,3,5,7] 返回 false ].
    • 现在我觉得还好
    • 这将适用于 [1,3,5,7],但对于 [1,3,5,8] 将失败,因为 diff 不等于 direction ( 3 != 2).
    • 是的,因为这是连续数字simple.wikipedia.org/wiki/Consecutive_integer
    • 引用问题:12345、45678、54321 都是正确的。而 435276、243516、974264 将是错误的
    猜你喜欢
    • 2016-01-03
    • 1970-01-01
    • 1970-01-01
    • 2016-01-16
    • 1970-01-01
    • 2013-08-02
    • 1970-01-01
    • 2022-11-10
    • 1970-01-01
    相关资源
    最近更新 更多