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

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(array &$board): void
{
    for ($row = 0; $row < BOARD_SIZE; $row++) {

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

        // Choose a random column index
        $randomCol = random_int(0, BOARD_SIZE - 1);

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

/*
 * printBoard:
 *   - Prints the 8x8 board in a readable grid format
 */
function printBoard(array $board): void
{
    for ($row = 0; $row < BOARD_SIZE; $row++) {
        for ($col = 0; $col < BOARD_SIZE; $col++) {
            echo $board[$row][$col] . " ";
        }
        echo PHP_EOL;
    }
}

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

$board = array_fill(0, BOARD_SIZE, array_fill(0, BOARD_SIZE, 0));

initializeBoard($board);
printBoard($board);


/*
run:

0 0 9 0 0 0 0 0 
0 0 0 0 82 0 0 0 
0 73 0 0 0 0 0 0 
13 0 0 0 0 0 0 0 
0 70 0 0 0 0 0 0 
0 0 0 0 0 0 99 0 
0 0 0 0 17 0 0 0 
0 0 0 0 0 0 87 0 

*/

 



answered 2 days ago by avibootz

Related questions

...