How to randomly place a random value in each row of an 8x8 int array with zero values in VB.NET

1 Answer

0 votes
Imports System

Module RandomBoard

    ' Board size constant for readability
    Private Const BoardSize As Integer = 8

    '---------------------------------------------------------------
    ' InitializeBoard:
    '   - Sets all values in the 8x8 array to zero
    '   - For each row:
    '       * randomly selects one column (0..7)
    '       * places a random integer (1..100) in that column
    '---------------------------------------------------------------
    Sub InitializeBoard(board As Integer(,))
        Dim rng As New Random()

        For row As Integer = 0 To BoardSize - 1

            ' Set entire row to zero
            For col As Integer = 0 To BoardSize - 1
                board(row, col) = 0
            Next

            ' Choose a random column index
            Dim randomCol As Integer = rng.Next(BoardSize)

            ' Place a random non-zero value (1..100)
            board(row, randomCol) = rng.Next(1, 101)

        Next
    End Sub

    '---------------------------------------------------------------
    ' PrintBoard:
    '   - Prints the 8x8 board in a readable grid format
    '---------------------------------------------------------------
    Sub PrintBoard(board As Integer(,))
        For row As Integer = 0 To BoardSize - 1
            For col As Integer = 0 To BoardSize - 1
                Console.Write($"{board(row, col),4}")
            Next
            Console.WriteLine()
        Next
    End Sub

    '---------------------------------------------------------------
    ' Main program
    '---------------------------------------------------------------
    Sub Main()
        Dim board(BoardSize - 1, BoardSize - 1) As Integer  ' Zero-initialized

        InitializeBoard(board)
        PrintBoard(board)
    End Sub

End Module


' run:
'
'   0   0   0   7   0   0   0   0
'  87   0   0   0   0   0   0   0
'   0   0   0   0  56   0   0   0
' 100   0   0   0   0   0   0   0
'   0   0   0   0   0   0  92   0
'   0   0   0   0  69   0   0   0
'   0   0   0   0  62   0   0   0
'   0  39   0   0   0   0   0   0
'

 



answered 2 days ago by avibootz

Related questions

...