How to fill a 3x3 grid to be a valid Sudoku grid in PHP

1 Answer

0 votes
// To fill a 3x3 grid to be a valid Sudoku grid, you must ensure that each row, 
// column, and the 3x3 grid contains the numbers 1 through 9 without repetition.

// Function to fill the Sudoku grid
function fillSudokuGrid(&$grid) {
    $numbers = range(1, 9);

    // Shuffle the numbers randomly
    shuffle($numbers);

    // Fill the 3x3 grid row by row
    $index = 0;
    for ($i = 0; $i < 3; $i++) {
        for ($j = 0; $j < 3; $j++) {
            $grid[$i][$j] = $numbers[$index++];
        }
    }
}

// Function to print the grid
function printGrid($grid) {
    foreach ($grid as $row) {
        foreach ($row as $num) {
            echo $num . " ";
        }
        echo "\n";
    }
}

// Initialize an empty 3x3 grid
$grid = array_fill(0, 3, array_fill(0, 3, 0));

// Fill the grid with a valid Sudoku configuration
fillSudokuGrid($grid);

// Print the grid
echo "Generated 3x3 Sudoku Grid:\n";
printGrid($grid);


  
/*
run:
  
Generated 3x3 Sudoku Grid:
7 9 4 
6 2 8 
3 5 1 
 
*/

 



answered Jun 1, 2025 by avibootz
edited Jun 1, 2025 by avibootz

Related questions

1 answer 157 views
1 answer 180 views
1 answer 146 views
1 answer 161 views
1 answer 179 views
...