How to select N unique random indices from an existing array in VB.NET

1 Answer

0 votes
Imports System
Imports System.Collections.Generic
Imports System.Linq

Module UniqueRandomIndices

    '---------------------------------------------------------------
    ' Select N unique random indices from an existing array.
    '
    ' Approach:
    ' - Build a list of indices: 0, 1, 2, ..., size-1.
    ' - Shuffle the list using Random + OrderBy.
    ' - Take the first N shuffled indices — guaranteed unique.
    ' - Return those indices to the caller.
    '---------------------------------------------------------------
    Function PickUniqueIndices(arraySize As Integer, count As Integer) As List(Of Integer)
        If count > arraySize Then
            Throw New ArgumentException("Cannot pick more unique indices than array size.")
        End If

        ' Build index list
        Dim indices As New List(Of Integer)(arraySize)
        For i As Integer = 0 To arraySize - 1
            indices.Add(i)
        Next

        ' Shuffle indices
        Dim rng As New Random()
        indices = indices.OrderBy(Function(x) rng.Next()).ToList()

        ' Return first N indices
        Return indices.Take(count).ToList()
    End Function

    Sub Main()
        ' Example array
        Dim data() As Integer = {5, 12, 5, 19, 5, 33, 47, 5, 58, 61, 17, 3, 5, 74, 83, 90, 6}

        Dim N As Integer = 6   ' number of unique indices to pick

        ' Get unique random indices
        Dim indices As List(Of Integer) = PickUniqueIndices(data.Length, N)

        ' Print results
        Console.WriteLine("Random unique indices and their values:")
        For Each idx In indices
            Console.WriteLine("index " & idx & " -> value " & data(idx))
        Next
    End Sub

End Module



' run:
'
' Random unique indices and their values:
' index 5 -> value 33
' index 10 -> value 17
' index 6 -> value 47
' index 2 -> value 5
' index 1 -> value 12
' index 12 -> value 5
' 

 



answered Sep 12 by avibootz

Related questions

...