Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function isValid(board, row, col, num) {
- // Check row and column
- for (let i = 0; i < 9; i++) {
- if (board[row][i] === num || board[i][col] === num) {
- return false;
- }
- }
- // Check 3x3 box
- const startRow = Math.floor(row / 3) * 3;
- const startCol = Math.floor(col / 3) * 3;
- for (let i = 0; i < 3; i++) {
- for (let j = 0; j < 3; j++) {
- if (board[startRow + i][startCol + j] === num) {
- return false;
- }
- }
- }
- return true;
- }
- function shuffle(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 solveSudoku(board) {
- for (let row = 0; row < 9; row++) {
- for (let col = 0; col < 9; col++) {
- if (board[row][col] === 0) {
- const numbers = shuffle([...Array(9).keys()].map(i => i + 1));
- for (const num of numbers) {
- if (isValid(board, row, col, num)) {
- board[row][col] = num;
- if (solveSudoku(board)) return true;
- board[row][col] = 0;
- }
- }
- return false; // No valid number found
- }
- }
- }
- return true; // Solved
- }
- function generateSudoku() {
- const board = Array.from({ length: 9 }, () => Array(9).fill(0));
- solveSudoku(board);
- return board;
- }
- // Generate and display the Sudoku grid
- const sudoku = generateSudoku();
- sudoku.forEach(row => console.log(row.join(' ')));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement