Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,914 questions

51,847 answers

573 users

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

1 Answer

0 votes
Imports System
Imports System.Collections.Generic

Public Class ArraySortedAndValidGap
	Public Shared Function IsArraySortedAndValidGap(ByVal list As List(Of Integer)) As Boolean
        If list.Count < 2 Then Return True
        Dim increasing As Boolean = list(1) > list(0)

        For i As Integer = 1 To list.Count - 1
            Dim diff As Integer = list(i) - list(i - 1)

            If diff <> 1 AndAlso diff <> 2 AndAlso diff <> 3 AndAlso diff <> -1 AndAlso diff <> -2 AndAlso diff <> -3 Then
                Return False
            End If

            If (increasing AndAlso diff <= 0) OrElse (Not increasing AndAlso diff >= 0) Then
                Return False
            End If
        Next

        Return True
    End Function

    Public Shared Sub Main()
		Dim list1 As List(Of Integer) = New List(Of Integer) From {
            1,
            2,
            3,
            5,
            8,
            11,
            14,
            15
        }

		If IsArraySortedAndValidGap(list1) Then
			Console.WriteLine("List is sorted and has valid gaps")
        Else
            Console.WriteLine("List is not sorted or gaps are invalid")
        End If

		Dim list2 As List(Of Integer) = New List(Of Integer) From {
            15,
            14,
            11,
            8,
            5,
            3,
            2,
            1
        }

		If IsArraySortedAndValidGap(list2) Then
            Console.WriteLine("List is sorted and has valid gaps")
        Else
            Console.WriteLine("List is not sorted or gaps are invalid")
        End If
    End Sub
End Class
 
 
  
' run:
'
' List is sorted and has valid gaps
' List is sorted and has valid gaps
'

 



answered Jan 12, 2025 by avibootz
...