To practice my JavaScript
for future employment, I’ve decided to take up the challenge of writing a javascript sudoku verifier. This code only verify’s one of the nine 3×3 blocks there are. I would like feedback on this portion of the code, so I can continue my development with more knowledge and more efficient code. Also, any feedback on my HTML/CSS
is warmly welcome. I’m using a fullscreen chrome browser for development, so the #middle
centers the box on my screen, but it might not on yours.
You will have to click on full page ->
to view the CSS
correctly.
function checkAnswer() { //reset each time button is clicked document.getElementById('correct').style.display = 'none'; document.getElementById('incorrect').style.display = 'none'; //add each input into 2D array let first_row = document.getElementsByClassName('row1'); let second_row = document.getElementsByClassName('row2'); let third_row = document.getElementsByClassName('row3'); let sudoku = [ [first_row[0].value, first_row[1].value, first_row[2].value], [second_row[0].value, second_row[1].value, second_row[2].value], [third_row[0].value, third_row[1].value, third_row[2].value] ] //check if each number is unique in the 2D array for (let i = 0; i < sudoku.length; i++) { for (let j = 0; j < sudoku[i].length; j++) { if(!isUnique(sudoku[i][j], sudoku)) { document.getElementById('incorrect').style.display = 'block'; return; } } } document.getElementById('correct').style.display = 'block'; } function isUnique(num, arr) { let count = 0; //check entire array for(let i = 0; i < arr.length; i++) { for(let j = 0; j < arr[i].length; j++) { if(arr[i][j] == num) { count++; } } } return count == 1; }
body { background-color: pink; } input { width: 50px; height: 50px; font-size: 20px; text-align: center; } button { width: 100px; height: 50px; font-size: 15px; margin-left: 40px; } #middle { margin-left: 900px; margin-top: 300px; }
<!DOCTYPE html> <html lang="en-US"> <head> <meta charset='UTF-8'> <title>Sudoku</title> <link rel="stylesheet" type="text/css" href="style.css"> <script src="script.js"></script> </head> <body> <div id="middle"> <table> <tr> <td><input type="text" class="row1" maxlength="1" value="3"></td> <td><input type="text" class="row1" maxlength="1"></td> <td><input type="text" class="row1" maxlength="1"></td> </tr> <tr> <td><input type="text" class="row2" maxlength="1"></td> <td><input type="text" class="row2" maxlength="1" value="2"></td> <td><input type="text" class="row2" maxlength="1"></td> </tr> <tr> <td><input type="text" class="row3" maxlength="1" value="7"></td> <td><input type="text" class="row3" maxlength="1"></td> <td><input type="text" class="row3" maxlength="1"></td> </tr> </table> <br> <button type="button" onclick="checkAnswer()">Check</button> <div id="incorrect" style="display: none;"> <h1>Incorrect Entry!</h1> </div> <div id="correct" style="display: none;"> <h1>Correct Entry!</h1> </div> </div> </body> </html>