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

1 Answer

0 votes
program SudokuGridGenerator;

// 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.

uses
  SysUtils;

const
  SIZE = 3;

type
  TGrid = array[1..SIZE, 1..SIZE] of Integer;

// Function to shuffle an array
procedure Shuffle(var arr: array of Integer; count: Integer);
var
  i, j, temp: Integer;
begin
  Randomize;
  for i := count - 1 downto 1 do
  begin
    j := Random(i + 1);
    temp := arr[i];
    arr[i] := arr[j];
    arr[j] := temp;
  end;
end;

// Function to fill the Sudoku grid
procedure FillSudokuGrid(var grid: TGrid);
var
  numbers: array[1..9] of Integer = (1, 2, 3, 4, 5, 6, 7, 8, 9);
  index, i, j: Integer;
begin
  Shuffle(numbers, 9);
  index := 1;

  for i := 1 to SIZE do
    for j := 1 to SIZE do
    begin
      grid[i, j] := numbers[index];
      Inc(index);
    end;
end;

// Function to print the grid
procedure PrintGrid(var grid: TGrid);
var
  i, j: Integer;
begin
  for i := 1 to SIZE do
  begin
    for j := 1 to SIZE do
      Write(grid[i, j], ' ');
    Writeln;
  end;
end;

var
  grid: TGrid;
begin
  FillSudokuGrid(grid);
  
  Writeln('Generated 3x3 Sudoku Grid:');
  PrintGrid(grid);
end.

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

 



answered Jun 1, 2025 by avibootz

Related questions

...