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,907 questions

51,839 answers

573 users

How to select N reservoir items randomly from an array in VB.NET

2 Answers

0 votes
Imports System
Imports System.Collections.Generic

Public Class Program
    Public Shared Function selectReservoir(ByVal arr As Integer(), ByVal N As Integer) As IList(Of Integer)
        Dim size As Integer = arr.Length
        Dim reservoir As IList(Of Integer) = New List(Of Integer)()
        Dim rand As Random = New Random()
        Dim items As Integer = 0

        While items < N
            Dim i As Integer = rand.[Next](0, size)
            Dim found As Boolean = False

            For j As Integer = 0 To items - 1
                If reservoir.Contains(arr(i)) Then
                    found = True
                    Exit For
                End If
            Next

            If Not found Then
                reservoir.Add(arr(i))
                items += 1
            End If
        End While

        Return reservoir
    End Function

    Public Shared Sub Main(ByVal args As String())
        Dim arr As Integer() = New Integer() {4, 9, 14, 96, 13, 0, 3, 99, 19, 2, 80, 1, 7}
        Dim N As Integer = 5

        Dim reservoir As IList(Of Integer) = selectReservoir(arr, N)

        Console.WriteLine(String.Join(" "c, reservoir))
    End Sub
End Class



' run:
'
' 99 4 7 1 13
'

 



answered Feb 3, 2024 by avibootz
0 votes
Imports System
Imports System.Linq

Public Class Program
    Public Shared Sub Main(ByVal args As String())
        Dim arr As Integer() = New Integer() {4, 9, 14, 96, 13, 0, 3, 99, 19, 2, 80, 1, 7}
        Dim N As Integer = 5
		
        Dim rand As Random = New Random()
		
        Dim reservoir = arr.OrderBy(Function(x) rand.[Next]()).Take(N)
	
        Console.WriteLine(String.Join(" "c, reservoir))
    End Sub
End Class




' run:
'
' 19 7 2 14 0
'

 



answered Feb 3, 2024 by avibootz

Related questions

1 answer 146 views
1 answer 111 views
2 answers 143 views
2 answers 121 views
2 answers 149 views
...