How to generate N random 1s in a zero-based matrix with VB.NET

1 Answer

0 votes
Imports System

Module RandomOnesMatrix

    '
    '   Generate N random 1s in a zero‑based matrix.
    '
    '   Strategy:
    '   - Treat the matrix as a flat index space [0 .. rows*cols - 1].
    '   - Randomly pick unique positions using a Boolean helper array.
    '   - Convert each chosen flat index back to (row, col).
    '   - This avoids repeatedly searching for empty cells and keeps the logic simple.
    '

    ' Print the matrix
    Sub PrintMatrix(matrix As Integer(,), rows As Integer, cols As Integer)
        For r = 0 To rows - 1
            For c = 0 To cols - 1
                Console.Write(matrix(r, c).ToString() & " ")
            Next
            Console.WriteLine()
        Next
    End Sub

    ' Allocate a rows×cols matrix initialized to zero
    Function AllocateMatrix(rows As Integer, cols As Integer) As Integer(,)
        Dim m(rows - 1, cols - 1) As Integer
        ' Elements are automatically initialized to zero
        Return m
    End Function

    ' Generate N random 1s in a zero-based matrix
    Function GenerateRandomMatrix(rows As Integer, cols As Integer, count As Integer) As Integer(,)
        Dim total As Integer = rows * cols

        If count > total Then
            Throw New ArgumentException("Requested more 1s than available cells.")
        End If

        ' Allocate the matrix
        Dim matrix As Integer(,) = AllocateMatrix(rows, cols)

        ' Temporary array to mark chosen positions
        Dim chosen(total - 1) As Boolean

        Dim rnd As New Random()

        ' Draw unique positions
        Dim placed As Integer = 0
        While placed < count
            Dim index As Integer = rnd.Next(total)
            If Not chosen(index) Then
                chosen(index) = True
                placed += 1
            End If
        End While

        ' Convert flat indices to (row, col)
        For i = 0 To total - 1
            If chosen(i) Then
                Dim r As Integer = i \ cols
                Dim c As Integer = i Mod cols
                matrix(r, c) = 1
            End If
        Next

        Return matrix
    End Function

    Sub Main()
        Dim rows As Integer = 5
        Dim cols As Integer = 7
        Dim numberOfOnes As Integer = 10

        Dim result As Integer(,) = GenerateRandomMatrix(rows, cols, numberOfOnes)

        PrintMatrix(result, rows, cols)
    End Sub

End Module



' run:
'
' 0 0 1 0 0 1 1 
' 0 1 0 0 1 0 1 
' 0 0 1 1 0 0 0 
' 0 1 0 0 0 0 0 
' 0 0 1 0 0 0 0
'

 



answered Aug 20 by avibootz
...