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

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

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

Disclosure: My content contains affiliate links.

43,563 questions

56,781 answers

573 users

How to find the element with minimum occurrences in an array with VB.NET

1 Answer

0 votes
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
'
					

 



answered Sep 25 by avibootz
...