How to check if a 3x3 grid is a valid Sudoku grid in Node.js

2 Answers

0 votes
// Sudoku solution must satisfy all of the following rules:
// Each of the digits 1-9 must occur once in each row.
// Each of the digits 1-9 must occur once in each column.
// Each of the digits 1-9 must occur once in each 3x3 grid.

function isValidSudoku3x3Grid(grid) {
    if (grid.length !== 3 || grid[0].length !== 3) {
        return false; // Ensure it's a 3x3 grid
    }

    let seen = new Set();
    for (let row of grid) {
        for (let num of row) {
            if (num < 1 || num > 9 || seen.has(num)) {
                return false; // Invalid if number is out of range or repeated
            }
            seen.add(num);
        }
    }

    return true; // Valid if all numbers 1-9 appear exactly once
}

const grid = [
    [5, 9, 1],
    [8, 7, 2],
    [4, 3, 6]
];

if (isValidSudoku3x3Grid(grid)) {
    console.log("The grid is a valid Sudoku grid!");
} else {
    console.log("The grid is NOT a valid Sudoku grid!");
}

  
  
/*
run:
      
The grid is a valid Sudoku grid!

*/
 

 



answered May 30, 2025 by avibootz
0 votes
// Sudoku solution must satisfy all of the following rules:
// Each of the digits 1-9 must occur once in each row.
// Each of the digits 1-9 must occur once in each column.
// Each of the digits 1-9 must occur once in each 3x3 grid.

function isValidSudoku3x3Grid(grid) {
    if (grid.length !== 3 || grid[0].length !== 3) {
        return false; // Ensure it's a 3x3 grid
    }

    let seen = new Set();
    for (let row of grid) {
        for (let num of row) {
            if (num < 1 || num > 9 || seen.has(num)) {
                return false; // Invalid if number is out of range or repeated
            }
            seen.add(num);
        }
    }

    return true; // Valid if all numbers 1-9 appear exactly once
}

// Export the function for use in other modules
module.exports = { isValidSudoku3x3Grid };

// Example usage
if (require.main === module) {
    const grid = [
        [5, 9, 1],
        [8, 7, 2],
        [4, 3, 6]
    ];

    if (isValidSudoku3x3Grid(grid)) {
        console.log("The grid is a valid Sudoku grid!");
    } else {
        console.log("The grid is NOT a valid Sudoku grid!");
    }
}

  
  
/*
run:
      
The grid is a valid Sudoku grid!

*/
 

 



answered May 30, 2025 by avibootz

Related questions

...