Imports System
Imports System.Collections.Generic
Imports System.Linq
Public Module FrequencyUtils
''' <summary>
''' Finds the element with the minimum number of occurrences in a collection.
''' </summary>
''' <typeparam name="T">The element type within the sequence.</typeparam>
''' <param name="sequence">The source sequence to inspect.</param>
''' <param name="minElement">When this method returns, contains the least frequent element if found.</param>
''' <returns>True if a minimum occurrence element was found; otherwise, False.</returns>
Public Function TryGetMinOccurrence(Of T)(sequence As IEnumerable(Of T), <System.Runtime.InteropServices.Out> ByRef minElement As T) As Boolean
minElement = Nothing
If sequence Is Nothing Then
Return False
End If
' Filter out nulls if T is a reference type
Dim validSequence = sequence.Where(Function(item) item IsNot Nothing)
If Not validSequence.Any() Then
Return False
End If
' Group elements, sort by count ascending, select the first key
minElement = validSequence _
.GroupBy(Function(item) item) _
.OrderBy(Function(grp) grp.Count()) _
.Select(Function(grp) grp.Key) _
.First()
Return True
End Function
Sub Main()
Dim arr As Integer() = {1, 3, 1, 1, 4, 4, 5, 5, 4, 2, 2, 2, 3, 3, 3}
Dim result As Integer
If TryGetMinOccurrence(arr, result) Then
Console.WriteLine(result) ' Output: 5
Else
Console.WriteLine("The array was empty or contained no valid elements.")
End If
End Sub
End Module
'
' run:
'
' 5
'