gpt-4.1-mini-2025-04-14· OpenAI
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
Certainly! Below is a Node.js code snippet that verifies if a given 9x9 matrix is a valid Sudoku board. The code checks the following Sudoku rules:
- Each row contains digits 1-9 without repetition.
- Each column contains digits 1-9 without repetition.
- Each of the nine 3x3 sub-boxes contains digits 1-9 without repetition.
Empty cells can be represented by
0or.(dot), and they are ignored in the validation.function isValidSudoku(board) { // Helper function to check if an array has duplicates ignoring zeros/dots function hasDuplicates(arr) { const seen = new Set(); for (const val of arr) { if (val === 0 || val === '.') continue; if (seen.has(val)) return true; seen.add(val); } return false; } // Check rows for (let i = 0; i < 9; i++) { if (hasDuplicates(board[i])) return false; } // Check columns for (let j = 0; j < 9; j++) { const col = []; for (let i = 0; i < 9; i++) { col.push(board[i][j]); } if (hasDuplicates(col)) return false; } // Check 3x3 sub-boxes for (let boxRow = 0; boxRow < 3; boxRow++) { for (let boxCol = 0; boxCol < 3; boxCol++) { const box = []; for (let i = 0; i < 3; i++) { for (let j = 0; j < 3; j++) { box.push(board[boxRow * 3 + i][boxCol * 3 + j]); } } if (hasDuplicates(box)) return false; } } return true; } // Example usage: const board = [ [5, 3, 0, 0, 7, 0, 0, 0, 0], [6, 0, 0, 1, 9, 5, 0, 0, 0], [0, 9, 8, 0, 0, 0, 0, 6, 0], [8, 0, 0, 0, 6, 0, 0, 0, 3], [4, 0, 0, 8, 0, 3, 0, 0, 1], [7, 0, 0, 0, 2, 0, 0, 0, 6], [0, 6, 0, 0, 0, 0, 2, 8, 0], [0, 0, 0, 4, 1, 9, 0, 0, 5], [0, 0, 0, 0, 8, 0, 0, 7, 9] ]; console.log(isValidSudoku(board)); // true or falseExplanation:
- The function
hasDuplicateschecks if an array contains any repeated numbers ignoring zeros or dots. - The main function checks all rows, columns, and 3x3 sub-boxes for duplicates.
- If any duplicates are found, it returns
false; otherwise, it returnstrue.
Let me know if you want me to handle other input formats or add more features!
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.