DOCTYPE html html lang en head meta charset UTF 8 meta name viewport content width device width initial scale 1 0 title 9x9 Grid of 3x3 Sudoku Grids title style body display flex justify content center align items center height 100vh margin 0 canvas border 1px solid black style head body canvas id sudokuCanvas width 450 height 450 canvas script const canvas document getElementById sudokuCanvas const ctx canvas getContext 2d const gridSize 3 3x3 subgrids const totalSize 9 9x9 grid const cellSize 50 Each cell is 50x50 pixels const size cellSize totalSize Total canvas size canvas width size canvas height size function drawGrid ctx clearRect 0 0 size size for let i 0 i totalSize i ctx beginPath ctx lineWidth i gridSize 0 4 1 ctx moveTo 0 i cellSize ctx lineTo size i cellSize ctx moveTo i cellSize 0 ctx lineTo i cellSize size ctx stroke function drawNumbers board ctx font cellSize 2 px Arial ctx textAlign center ctx textBaseline middle for let row 0 row totalSize row for let col 0 col totalSize col if board row col 0 ctx fillText board row col col cellSize cellSize 2 row cellSize cellSize 2 function isValid board row col num for let x 0 x totalSize x if board row x num board x col num return false const boxRow Math floor row gridSize gridSize Math floor x gridSize const boxCol Math floor col gridSize gridSize x gridSize if board boxRow boxCol num return false return true function generateSudoku board for let row 0 row totalSize row for let col 0 col totalSize col if board row col 0 let numbers Array from length totalSize _ i i 1 numbers shuffleArray numbers for let num of numbers if isValid board row col num board row col num if generateSudoku board return true board row col 0 return false return true function shuffleArray array for let i array length 1 i 0 i const j Math floor Math random i 1 array i array j array j array i return array function generateBoard let board Array from length totalSize Array totalSize fill 0 generateSudoku board return board function main let board generateBoard drawGrid drawNumbers board main script body html
if board row x num board x col num return false const boxRow Math floor row gridSize gridSize Math floor x gridSize const boxCol Math floor col gridSize gridSize x gridSize if board boxRow boxCol num return false return true function generateSudoku board for let row 0 row totalSize row for let col 0 col totalSize col if board row col 0 let numbers Array from length totalSize _ i i 1 numbers shuffleArray numbers for let num of numbers if isValid board row col num board row col num if generateSudoku board return true board row col 0 return false return true function shuffleArray array for let i array length 1 i 0 i const j Math floor Math random i 1 array i array j array j array i return array function generateBoard let board Array from length totalSize Array totalSize fill 0 generateSudoku board return board function main let board generateBoard drawGrid drawNumbers board main script body html