How to check if a list is all increasing or decreasing and the gap between numbers is 1, 2 or 3 in C#

1 Answer

0 votes
using System;
using System.Collections.Generic;

class ArraySortedAndValidGap
{
    static bool IsArraySortedAndValidGap(List<int> list) {
        if (list.Count < 2) return true;

        bool increasing = list[1] > list[0];
        for (int i = 1; i < list.Count; i++) {
            int diff = list[i] - list[i - 1];
            if (diff != 1 && diff != 2 && diff != 3 && diff != -1 && diff != -2 && diff != -3) {
                return false;
            }
            if ((increasing && diff <= 0) || (!increasing && diff >= 0)) {
                return false;
            }
        }
        
        return true;
    }

    static void Main()
    {
        List<int> list1 = new List<int> { 1, 2, 3, 5, 8, 11, 14, 15 };

        if (IsArraySortedAndValidGap(list1)) {
            Console.WriteLine("Array is sorted and has valid gaps");
        }
        else {
            Console.WriteLine("Array is not sorted or gaps are invalid");
        }

        List<int> list2 = new List<int> { 15, 14, 11, 8, 5, 3, 2, 1 };

        if (IsArraySortedAndValidGap(list2)) {
            Console.WriteLine("Array is sorted and has valid gaps");
        } 
        else {
            Console.WriteLine("Array is not sorted or gaps are invalid");
        }
    }
}



/*
run:

Array is sorted and has valid gaps
Array is sorted and has valid gaps
   
*/

 



answered Jan 12, 2025 by avibootz
...