How to randomly place a random value in each row of an 8x8 int list with zero values in JavaScript

1 Answer

0 votes
/*
 * This program creates an 8x8 integer board.
 * For each row:
 *   - All values are set to zero
 *   - One random column is chosen
 *   - A random value (1..100) is placed in that column
 *
 * It mirrors the structure of the C++ version:
 *   initializeBoard()
 *   printBoard()
 *   main logic
 */

const BOARD_SIZE = 8;

/*
 * initializeBoard:
 *   - Sets all values to zero
 *   - For each row:
 *       * randomly selects one column (0..7)
 *       * places a random integer (1..100) in that column
 */
function initializeBoard(board) {
    for (let row = 0; row < BOARD_SIZE; row++) {

        // Set entire row to zero
        for (let col = 0; col < BOARD_SIZE; col++) {
            board[row][col] = 0;
        }

        // Choose a random column index
        const randomCol = Math.floor(Math.random() * BOARD_SIZE);

        // Place a random non-zero value (1..100)
        const randomValue = Math.floor(Math.random() * 100) + 1;

        board[row][randomCol] = randomValue;
    }
}

/*
 * printBoard:
 *   - Prints the 8x8 board in a readable grid format
 */
function printBoard(board) {
    for (let row = 0; row < BOARD_SIZE; row++) {
        console.log(board[row].join(" "));
    }
}

// ------------------------
// Main program
// ------------------------

const board = Array.from({ length: BOARD_SIZE }, () =>
    Array.from({ length: BOARD_SIZE }, () => 0)
);

initializeBoard(board);
printBoard(board);


/*
run:

0 0 0 0 0 46 0 0
0 0 0 0 11 0 0 0
51 0 0 0 0 0 0 0
0 0 71 0 0 0 0 0
0 0 0 0 0 25 0 0
0 0 0 0 0 0 44 0
0 0 0 0 67 0 0 0
0 68 0 0 0 0 0 0

*/

 



answered 2 days ago by avibootz

Related questions

...