Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

หาตัวเลขที่หายไปในลำดับใน C#

ใช้ Enumerable.Range สร้างลำดับตัวเลขครบถ้วนจากค่าต่ำสุดถึงค่าสูงสุด แล้วใช้ Except หาค่าที่อยู่ในลำดับครบแต่ไม่อยู่ในลำดับต้นฉบับ

ตัวอย่างโค้ด

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
        List myList = new List { 1, 2, 3, 5, 8, 9 };
        
        int a = myList.OrderBy(x => x).First();   // 1
        int b = myList.OrderBy(x => x).Last();    // 9
        
        List fullRange = Enumerable.Range(a, b - a + 1).ToList(); // 1..9
        List missing = fullRange.Except(myList).ToList();         // 4,6,7
        
        Console.WriteLine("Missing numbers:");
        foreach (int res in missing) Console.WriteLine(res);
    }
}

ผลลัพธ์

Missing numbers:
4
6
7

สมมติฐาน: ลำดับเป็นจำนวนเต็มเรียงติดกัน (Consecutive Integers)