const canvas document createElement canvas document body appendChild canvas const ctx canvas getContext 2d const size 450 const rows 9 const cols 9 const cellSize size rows function drawGrid ctx beginPath for let i 0 i rows i let lineWidth i 3 0 2 1 ctx lineWidth lineWidth 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 rows row for let col 0 col cols 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 9 x if board row x num board x col num board 3 Math floor row 3 Math floor x 3 3 Math floor col 3 x 3 num return false return true function generateSudoku board for let row 0 row rows row for let col 0 col cols col if board row col 0 for let num 1 num 9 num if isValid board row col num board row col num if generateSudoku board return true board row col 0 return false return true function removeNumbers board count while count 0 let row Math floor Math random rows let col Math floor Math random cols if board row col 0 board row col 0 count function generateBoard let board Array from length rows Array cols fill 0 generateSudoku board removeNumbers board 40 Remove 40 numbers to create a puzzle return board function main let board generateBoard drawGrid drawNumbers board main
return true function generateSudoku board for let row 0 row rows row for let col 0 col cols col if board row col 0 for let num 1 num 9 num if isValid board row col num board row col num if generateSudoku board return true board row col 0 return false return true function removeNumbers board count while count 0 let row Math floor Math random rows let col Math floor Math random cols if board row col 0 board row col 0 count function generateBoard let board Array from length rows Array cols fill 0 generateSudoku board removeNumbers board 40 Remove 40 numbers to create a puzzle return board function main let board generateBoard drawGrid drawNumbers board main