How to fill a matrix with 1 and 0 in random locations with VB.NET

1 Answer

0 votes
Imports System

Public Class FillMatrixWith1And0InRandomLocations
    Const ROWS As Integer = 5
    Const COLS As Integer = 4

    Public Shared Sub Main(ByVal args As String())
        Dim matrix As Integer(,) = New Integer(4, 3) {}
		
        FillMatrixWithRandom0and1(matrix, ROWS, COLS)
		
        PrintMatrix(matrix, ROWS, COLS)
    End Sub

    Public Shared Sub FillMatrixWithRandom0and1(ByVal matrix As Integer(,), ByVal rows As Integer, ByVal cols As Integer)
        Dim rand As Random = New Random()

        For i As Integer = 0 To rows - 1
            For j As Integer = 0 To cols - 1
                matrix(i, j) = rand.Next(2)
            Next
        Next
    End Sub

	Public Shared Sub PrintMatrix(ByVal matrix As Integer(,), ByVal rows As Integer, ByVal cols As Integer)
        For i As Integer = 0 To rows - 1
            For j As Integer = 0 To cols - 1
                Console.Write(matrix(i, j) & " ")
            Next

            Console.WriteLine()
        Next
    End Sub
End Class



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

 



answered Jan 25, 2025 by avibootz

Related questions

1 answer 158 views
1 answer 194 views
1 answer 200 views
1 answer 186 views
1 answer 191 views
1 answer 195 views
...