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

1 Answer

0 votes
#include <array>
#include <iostream>
#include <random>

// Type alias for readability
using Board = std::array<std::array<int, 8>, 8>;

/*
 * initializeBoard:
 *   - Sets all values to zero
 *   - For each row, chooses one random column
 *   - Places a random integer in that column
 */
void initializeBoard(Board& board) {
    // Modern C++ random engine and distributions
    std::random_device rd;                 // Non-deterministic seed
    std::mt19937 gen(rd());                // Fast Mersenne Twister engine
    std::uniform_int_distribution<> colDist(0, 7);   // Random column index
    std::uniform_int_distribution<> valDist(1, 100); // Random value range

    for (auto& row : board) {
        // Set entire row to zero
        row.fill(0);

        // Choose a random column
        int col = colDist(gen);

        // Place a random value in that column
        row[col] = valDist(gen);
    }
}

/*
 * printBoard:
 *   - Prints the 8x8 board in a readable format
 */
void printBoard(const Board& board) {
    for (const auto& row : board) {
        for (int value : row) {
            std::cout << value << ' ';
        }
        std::cout << '\n';
    }
}

int main() {
    Board board{};        // Zero-initialized by default
    
    initializeBoard(board);
    
    printBoard(board);
}



/*
run:

0 0 0 0 0 0 90 0 
0 0 0 0 6 0 0 0 
0 0 14 0 0 0 0 0 
0 0 0 0 0 75 0 0 
0 0 0 0 0 0 0 99 
0 90 0 0 0 0 0 0 
0 0 0 0 35 0 0 0 
0 0 0 0 0 0 0 71 

*/

 



answered 2 days ago by avibootz

Related questions

...