qwen3-235b-a22b-no-thinking· Alibaba (Qwen) LMArena Human Preference 140K
Given a matrix, creates a nodejs code that verify if it is a valid sudoku game
- User
Given a matrix, creates a nodejs code that verify if it is a valid sudoku game
- Assistant
Here's a Node.js script that verifies whether a given 9x9 matrix is a valid Sudoku board.
✅ Rules for Valid Sudoku (Partial Game):
- Each row must contain digits
1-9without repetition. - Each column must contain digits
1-9without repetition. - Each of the 9
3x3subgrids must contain digits1-9without repetition. - Empty cells (represented by
.or0) are allowed in an incomplete game.
✅ Node.js Code:
sudokuValidator.jsfunction isValidSudoku(board) { const SIZE = 9; const SUBGRID_SIZE = 3; // Use sets to track numbers in rows, columns, and subgrids const rowSets = Array.from({ length: SIZE }, () => new Set()); const colSets = Array.from({ length: SIZE }, () => new Set()); const subgridSets = Array.from({ length: SIZE }, () => new Set()); for (let row = 0; row < SIZE; row++) { for (let col = 0; col < SIZE; col++) { const cell = board[row][col]; // Skip empty cells if (cell === '.' || cell === 0 || cell === '') { continue; } const num = cell; // Check row if (rowSets[row].has(num)) { console.log(`Duplicate in row ${row + 1}: ${num}`); return false; } rowSets[row].add(num); // Check column if (colSets[col].has(num)) { console.log(`Duplicate in column ${col + 1}: ${num}`); return false; } colSets[col].add(num); // Check subgrid const subgridIndex = Math.floor(row / SUBGRID_SIZE) * SUBGRID_SIZE + Math.floor(col / SUBGRID_SIZE); if (subgridSets[subgridIndex].has(num)) { console.log(`Duplicate in subgrid ${subgridIndex + 1}: ${num}`); return false; } subgridSets[subgridIndex].add(num); } } return true; } // Example usage: const sudokuBoard = [ [5, 3, '.', '.', 7, '.', '.', '.', '.'], [6, '.', '.', 1, 9, 5, '.', '.', '.'], ['.', 9, 8, '.', '.', '.', '.', 6, '.'], [8, '.', '.', '.', 6, '.', '.', '.', 3], [4, '.', '.', 8, '.', 3, '.', '.', 1], [7, '.', '.', '.', 2, '.', '.', '.', 6], ['.', 6, '.', '.', '.', '.', 2, 8, '.'], ['.', '.', '.', 4, 1, 9, '.', '.', 5], ['.', '.', '.', '.', 8, '.', '.', 7, 9] ]; console.log(isValidSudoku(sudokuBoard) ? "Valid Sudoku" : "Invalid Sudoku");
📝 Notes:
- You can represent empty cells using
'.',0, or any falsy value ('',null, etc.) — just update the check accordingly. - This code only checks for duplicates, not if the Sudoku is solvable. That would require backtracking logic.
- Works both for partial and complete boards.
▶️ Run it with Node.js
Save as
sudokuValidator.jsand run:node sudokuValidator.jsLet me know if you want to validate a full solution or read from a file!
- Each row must contain digits
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.