簡體   English   中英

在c#中查找連續的數字

[英]Finding consecutive numbers in c#

這是我的練習..

編寫一個程序並要求用戶輸入幾個用連字符隔開的數字。 確定數字是否連續。

例如,如果輸入是5-6-7-8-9 ,則顯示一條消息: Consecutive 如果輸入5-1-8-2顯示Not Consecutive

這是我的方法。

namespace ConsoleApp7
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter numbers separate by hypen : ");
            var name = Console.ReadLine();
            var numarray = name.Split('-');
            for (var i = 0;i<=numarray.Length-1;i++ )
            {
                if (i>1 && (Convert.ToInt32(numarray[i]) != Convert.ToInt32(numarray[i - 1])+1))
                {
                    Console.WriteLine("Not Consecutive");
                    break;
                }
                if (i == numarray.Length-1)
                {
                    Console.WriteLine("Consecutive");
                }

            }
        }
    }
}

它奏效了。 有沒有更好/簡化的方法。

你可以這樣簡化,

 static void Main(string[] args)
    {
        Console.WriteLine("Enter numbers separate by hypen : ");
        var name = Console.ReadLine();
        int[] numarray = Array.ConvertAll(name.Split('-'), int.Parse); 
        if (IsSequential(numarray))
        {
            Console.WriteLine("Consecutive");
        }
        else
        {
            Console.WriteLine("Not Consecutive");                 
        }
    }
    static bool IsSequential(int[] array)
    {
        return array.Zip(array.Skip(1), (a, b) => (a + 1) == b).All(x => x);
    }

這是最有效的方法:

using System;

namespace ConsoleApp7
{
    public class Program
    {
        public static void Main(string[] args)
        {
        Console.WriteLine("Enter numbers separate by hypen : ");
        var name = Console.ReadLine();
        var numarray = name.Split('-');
        int firstValue = Convert.ToInt32(numarray[0]);

        bool cons = true;
        for (var i = 0;i<numarray.Length;i++ )
        {
            if (Convert.ToInt32(numarray[i])-i != firstValue)
            {
                cons = false;                   
                break;
            }
        }
        if (cons)
        {
            Console.WriteLine("Consecutive");
        }
        else
        {
            Console.WriteLine("Not Consecutive");
        }
    }
}

}

https://dotnetfiddle.net/P8VGjG

考慮這樣的方法:

    static void Main(string[] args)
    {
        Console.WriteLine("Enter numbers separate by hypen : ");
        var name = Console.ReadLine();
        var numarray = name.Split('-');
        var lower = int.Parse(numarray[0]);
        Console.WriteLine(Enumerable.Range(lower, numarray.Length)
            .Select(z => z.ToString()).SequenceEqual(numarray)
            ? "Consecutive"
            : "Not");

        Console.ReadLine();
    }

(更好的是,使用 TryParse 以防第一個條目不是數字)

我試過這個,它工作得很好,它是連續的向前和向后。 也很簡單。 它看起來很長,因為我喜歡評論。

 static void Main(string[] args)
    {
        //This Variables checks if the secuence continues
        bool secuence = true;

        //Ask Receive Input
        Console.Write("Enter dashed numbers: ");
        string[] input = Console.ReadLine().Split('-');

        //Convert to Integer
        int[] numbers = Array.ConvertAll(input, int.Parse);

        //Loop Through all the values
        for(int i = 1; i<numbers.Length; i++)
        {
            //check if current value is +1 greater than last value
            if (numbers[i] + 1 == numbers[i - 1] || numbers[i]-1 == numbers[i - 1] && secuence == true)
            {   //continue counting if consecutive
                secuence = true;
            }
            else
            {   //Stop Counting if not consecutive
                secuence = false;
            }
        }
        //Workout the result
        if (secuence)
        {
            Console.WriteLine("The Numbers are consecutive");
        }
        else 
        { 
            Console.WriteLine("They are not consecutive"); 
        }
    }

這是我對問題的回答。 它將適用於場景

  1. 3- ==> 不連續
  2. 4 => 不連續
  3. 3-4-5-6 => 連續
  4. 3-4-5- => 連續
  5. 3-4-5-5-6 => N
using System;

namespace ConsecutiveNumbers
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter the number seperated by hyphen : ");
            var input = Console.ReadLine();
            var numArray = input.Split('-');
            var firstValue = numArray[0];
            var output = "Consecutive";

            if (numArray.Length > 2)
            {
                for (var i = 0; i < numArray.Length; i++)
                {
                    if (!string.IsNullOrWhiteSpace(numArray[i]))
                    {
                        if (i != 0)
                        {
                            if (int.Parse(numArray[i]) - int.Parse(firstValue) == 1)
                            {
                                //Console.WriteLine(int.Parse(numArray[i]) - int.Parse(firstValue));
                                firstValue = numArray[i];
                            }
                            else
                            {
                                output = "Not Consecutive";
                                break;
                            }
                        }
                        
                    }
                }
            }
            else
            {
                output = "Not Consecutive";
            }

            Console.WriteLine(output);
        }
        
    }
}

這是簡短而簡單的解決方案:

public void Question6()
    {
        Console.WriteLine("Enter few number separated by hyphen.");
        var input = Console.ReadLine(),;
        var array = input.Split('-');
        Array.Sort(array);
        var output = "Consecutive";
        var arrayData = array[0];

        for (int i = 0; i < array.Length; i++)
        {
            if (i != 0)
            {
                if (int.Parse(array[i]) - int.Parse(arrayData) == 1)
                {
                    arrayData = array[i];
                }
                else
                {
                    output = "Not Consecutive";
                    break;
                }
            }

        }
        Console.WriteLine(output);
    }

這是我的代碼。

一種簡單易讀的方法。

Console.WriteLine("Type a series of number separated by hyphen: ");
var input = Console.ReadLine();

var series = input.Split("-")
       .Select(n => Convert.ToInt32(n));

var isConsecutive = Enumerable
      .Range(series.First(), series.Count())
      .SequenceEqual(series);

Console.WriteLine(isConsecutive ? "Consecutive"  : "Not Consecutive");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM