How to find the floor and ceiling of the value N in an unsorted list with VB.NET

1 Answer

0 votes
Imports System
Imports System.Collections.Generic

Module FloorCeilFinder

    ' Finds the floor and ceiling of N in the given list
    Function FindFloorAndCeil(lst As List(Of Integer), N As Integer) As (Floor As Integer, Ceil As Integer)
        Dim floorval As Integer = Integer.MinValue ' Initialize to the smallest possible value
        Dim ceilval As Integer = Integer.MaxValue  ' Initialize to the largest possible value

        For Each num In lst
            If num <= N AndAlso num > floorval Then
                floorval = num ' Update floorval if num is closer to N
            End If
            If num >= N AndAlso num < ceilval Then
                ceilval = num ' Update ceilval if num is closer to N
            End If
        Next

        ' If no valid floorval or ceilval is found, set them to a special value
        If floorval = Integer.MinValue Then floorval = -1
        If ceilval = Integer.MaxValue Then ceilval = -1

        Return (floorval, ceilval)
    End Function

    Sub Main()
		Dim lst As New List(Of Integer) From {4, 10, 8, 2, 6, 9, 1}
        Dim N As Integer = 5

        Dim result = FindFloorAndCeil(lst, N)
        Dim floorval = result.Floor
        Dim ceilval = result.Ceil

        Console.WriteLine("floor: " & If(floorval = -1, "None", floorval.ToString()))
        Console.WriteLine("ceil: " & If(ceilval = -1, "None", ceilval.ToString()))
    End Sub

End Module
			
			
' run:
'
' floor: 4
' ceil: 6
'

 



answered Nov 8 by avibootz
...