Advertisement
EntropyStarRover

sudoku board

Jun 10th, 2025
449
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function isValid(board, row, col, num) {
  2.   // Check row and column
  3.   for (let i = 0; i < 9; i++) {
  4.     if (board[row][i] === num || board[i][col] === num) {
  5.       return false;
  6.     }
  7.   }
  8.  
  9.   // Check 3x3 box
  10.   const startRow = Math.floor(row / 3) * 3;
  11.   const startCol = Math.floor(col / 3) * 3;
  12.   for (let i = 0; i < 3; i++) {
  13.     for (let j = 0; j < 3; j++) {
  14.       if (board[startRow + i][startCol + j] === num) {
  15.         return false;
  16.       }
  17.     }
  18.   }
  19.  
  20.   return true;
  21. }
  22.  
  23. function shuffle(array) {
  24.   for (let i = array.length - 1; i > 0; i--) {
  25.     const j = Math.floor(Math.random() * (i + 1));
  26.     [array[i], array[j]] = [array[j], array[i]];
  27.   }
  28.   return array;
  29. }
  30.  
  31. function solveSudoku(board) {
  32.   for (let row = 0; row < 9; row++) {
  33.     for (let col = 0; col < 9; col++) {
  34.       if (board[row][col] === 0) {
  35.         const numbers = shuffle([...Array(9).keys()].map(i => i + 1));
  36.         for (const num of numbers) {
  37.           if (isValid(board, row, col, num)) {
  38.             board[row][col] = num;
  39.             if (solveSudoku(board)) return true;
  40.             board[row][col] = 0;
  41.           }
  42.         }
  43.         return false; // No valid number found
  44.       }
  45.     }
  46.   }
  47.   return true; // Solved
  48. }
  49.  
  50. function generateSudoku() {
  51.   const board = Array.from({ length: 9 }, () => Array(9).fill(0));
  52.   solveSudoku(board);
  53.   return board;
  54. }
  55.  
  56. // Generate and display the Sudoku grid
  57. const sudoku = generateSudoku();
  58. sudoku.forEach(row => console.log(row.join(' ')));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement