Checking Sudoku Solutions on Codewars

I have come across this JavaScript code which seems to be functioning correctly. However, I am curious about the line board[3][8] != board[8][3] and how it checks for repeating row and column numbers. Can someone please provide an explanation? Thank you!

function validSolution(board) {
    let count0 = 0;
    let count1 = 0;
    let count2 = 0;
    let count3 = 0;
    let count4 = 0;
    let count5 = 0;
    let count6 = 0;
    let count7 = 0;
    let count8 = 0;
    let count9 = 0;
    
    for (let i = 0; i < board.length; i++) {
        count0 += board[i][0];
        count1 += board[i][1];
        count2 += board[i][2];
        count3 += board[i][3];
        count4 += board[i][4];
        count5 += board[i][5];
        count6 += board[i][6];
        count7 += board[i][7];
        count8 += board[i][8];
    }

    return (count0 === 45 && count1 === 45 && count2 === 45 && count3 === 45 
        && count4 === 45 && count5 === 45 && count6 === 45 && count7 === 45 &&
        count8 === 45 && board[3][8] != board[8][3] );
}

Answer №1

Ensuring some variation in the numbers on the board through an additional check does not guarantee that the solution is valid.

Consider this example board:

let board = [
 [5,5,5,5,5,5,5,5,5],
 [5,5,5,5,5,5,5,5,5],
 [5,5,5,5,5,5,5,5,5],
 [4,5,5,5,5,5,5,5,6],
 [5,5,5,5,5,5,5,5,5],
 [6,5,5,5,5,5,5,5,4],
 [5,5,5,5,5,5,5,5,5],
 [5,5,5,5,5,5,5,5,5],
 [5,5,5,5,5,5,5,5,5]
];

All rows total 45, yet positions [3][8] and [8][3] are not equal. Despite this, validSolution mistakenly recognizes this board as valid...

Another validation method I devised:

function validSolution(board) {
  var boardx = board.map(x => new Set(x).size == 9 ? x.reduce((a,b) => a+b, 0) : 0);
  var boardy = board[0].map((x,col,b) => board.map(x => x[col])).map(x => new Set(x).size == 9 ? x.reduce((a,b) => a+b, 0) : 0);
  return new Set(boardx).size == 1 && boardx[0] == 45 && new Set(boardy).size == 1 && boardy[0] == 45;
}

A brief explanation:

boardx calculates each row's sum (x.reduce((a,b) => a+b, 0)) if it contains 9 unique values (new Set(x).size == 9 1)

boardy computes the sum of each column after 'rotating' the grid (

board[0].map((x,col,b) => board.map(x => x[col]))
, followed by a similar process as above.

In a valid board, both boardx and boardy must consist of 9 elements with a value of 45. Therefore, we verify if both arrays contain only one unique value, which is 45.


1 The Set object stores unique values, making it ideal for quickly checking array uniqueness.

Answer №2

Is it really important to note that [8][3] is not equal to [3][8]? In the game of sudoku, these cells are completely independent of each other.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a draggable element in JavaScript using React

I've been attempting to create a draggable div element, but I'm encountering some perplexing behavior. The code I'm using is directly from w3schools and it functions correctly for them, however, in my implementation, the div always shifts to ...

Exploring Node.js and JSON: Retrieving specific object attributes

Utilizing ExpressJS, NodeJS, and Bookshelf.js In an attempt to display a user's list of friends, encountering the error "Unhandled rejection TypeError: Cannot read property 'friends' of undefined" when trying to access a property of the obj ...

Removing other objects with Mongoose after an update

I'm facing an issue with my update query in mongoose. I can't figure out why other objects are getting deleted when I only intend to update one specific object. The code is functioning correctly in terms of updating, but it's causing all the ...

Verifying user login on NodeJS through connection from an IIS-hosted website

I am currently upgrading an outdated CMS system and looking to implement a real-time chat feature. The existing CMS operates on IIS, MSSQL, and PHP. The chat feature will be hosted on a separate Linux box running Node.js and Socket.io After successfully ...

What is the best way to save a jQuery or JavaScript variable into a JSON file?

Is there a way to save a jquery variable in a json file? I have the following: var image='/test/test.png'; I am obtaining this path through file upload: <input type="file" name="imageurl" value="imagefile"></input> Therefore, I ne ...

Adjust the size of the mat-expansion indicator to your desired height and width

Trying to modify the width and height of the mat indicator has been a bit challenging. Despite following suggestions from other similar questions, such as adjusting the border width and padding, I am still unable to see the changes reflect in my CSS file ...

The 'name' property of Axios and Vuex is not defined and cannot be read

When making a call to axios in my mounted function to retrieve profile data, I send the payload to the 'set_account' Vuex store upon success. To access this data, I utilize MapGetters (currentAccount) in computed properties. However, when tryin ...

The date range picker displays the previous arrow but not the next arrow

I am currently using the DateRangePicker tool and for some reason, I am not seeing the arrow that should appear on the right side. I have double-checked my configuration but can't seem to figure out what is causing this issue. In the image attached, ...

Concern raised about the challenge of removing an element from an array and its potential

When attempting to remove an element from an array without altering the state, I typically use the following code snippet: const tempArray = [ ...originalArray ]; tempArray.splice(index, 1); setOriginalArray(tempArray); After some experimentation, I deci ...

Flot seems to be having difficulty uploading JSON files

I am relatively new to working with json and flot, but have been tasked with creating a chart. Can someone please help me troubleshoot why my code is not functioning as expected? $.getJSON('chart.json', function(graphData){ alert(graphData); ...

How to prevent checkbox autocomplete from selecting the previously checked value using Jquery Ajax

Working on implementing the "Autocomplete ajax search" feature using Php. Successfully fetching data from the database. Currently, when searching for something, the results with checkboxes are displayed. However, when I search for a text, check a checkbo ...

What is the best way to transfer data entered into a textbox through an onclick Alert event into a database?

UI https://i.stack.imgur.com/c2cqo.png Here is the PHP code I have been struggling with. It is meant to save input data into a database, but I can't seem to get it right: if (isset($_POST['rjctrsn-data']) && !empty($_POST['rjc ...

Using AJAX with the GET method, send a form submission to retrieve a response using XMLHTTPRequest

I am working on a form where users can select values from two dropdown menus. The options in the dropdowns are populated dynamically from a JavaScript file, which contains a list of exchange rates. I have written the code to calculate and display the resul ...

Enhance the styling of elements generated through JavaScript in VueJs with custom CSS

I need help applying CSS to elements that I dynamically created using JavaScript. buttonClicked(event) { console.log(event); let x = event.clientX - event.target.offsetLeft; let y = event.clientY - event.target.offsetTop; let ripples = document.cre ...

When utilizing the React onclick function, it generates an increase in state values rather than modifying

I'm currently working on a function that changes the state property, "changedMarkup", when a button is clicked. Initialization constructor() { super(); this.state = { value: 0, changedMarkup: 0 }; } Render Function render() ...

Tips for displaying a message when clicking on the second level in fancytree.js

I'm looking to use fancytree.js to display an alert message only when clicking on nodes in the second level. For example: <ul> <li>1</li> <ul> <li>1.1</li> ...

Running Javascript based on the output of PHP code

I have been working on my code with test.php that should trigger some Javascript when my PHP code, conditional.php, detects input and submits it. However, instead of executing the expected "Do Something in Javascript," it outputs "Not empty" instead. I fin ...

What is the best way to save the data received from createApi into the Redux store?

Currently, I am faced with the challenge of storing user data (such as name, email, etc.) obtained through the createApi function into Redux store. However, I'm unsure of the best practice to achieve this. In my userApi.js file: export const userApi ...

Interactive back button for seamless navigation back to the originating modal

This website is built on Bootstrap 4. As I develop this site, there are a total of 17 different modals. Specific words in each modal are linked to other modals for additional information. However, getting back to the previous modal requires closing the ...

Struggling with making changes to a instantiated "this" object within a pseudo javascript class

If you scroll down to the bottom of this post, you'll find a workaround or possible solution. I've been grappling with understanding how pseudo classes work together to achieve the task I'm attempting (explained in the code below). It might ...