How to randomly place a random value in each row of an 8x8 int array with zero values in C#

1 Answer

0 votes
using System;

class RandomBoard
{
    private const int BoardSize = 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
     */
    static void InitializeBoard(int[,] board)
    {
        Random rng = new Random();

        for (int row = 0; row < BoardSize; row++) {
            // Set entire row to zero
            for (int col = 0; col < BoardSize; col++)
                board[row, col] = 0;

            // Choose a random column index
            int randomCol = rng.Next(BoardSize);

            // Place a random non-zero value (1..100)
            board[row, randomCol] = rng.Next(1, 101);
        }
    }

    /*
     * PrintBoard:
     *   - Prints the 8x8 board in a readable grid format
     */
    static void PrintBoard(int[,] board)
    {
        for (int row = 0; row < BoardSize; row++) {
            for (int col = 0; col < BoardSize; col++)
                Console.Write($"{board[row, col],4}");
            Console.WriteLine();
        }
    }

    static void Main()
    {
        int[,] board = new int[BoardSize, BoardSize]; // Zero-initialized

        InitializeBoard(board);
        PrintBoard(board);
    }
}


/*
run:

   0   0   0   0   0   0   0  82
   0   0  39   0   0   0   0   0
   0   0  23   0   0   0   0   0
   0   0   0   0   0   0  59   0
   0   0   0   0  87   0   0   0
  99   0   0   0   0   0   0   0
   0   0   0   0   0   0   0  88
   0   0   0   0   0   0  99   0

*/

 



answered 2 days ago by avibootz

Related questions

...