Can you explain the purpose of N-2 in the Sudoku for loop when validating the block in JavaScript?

After delving into the Sudoku Solution Validator algorithm, I stumbled upon an interesting example. The code seems to work perfectly and validates the solution. However, one thing that perplexes me is why there is a N-2 in the for loops when trying to validate a block. If N = 9 and the board is 9 * 9, shouldn't it stay as 9 instead of being changed to 7?

I experimented by removing the -2 and sticking with just N, but I didn't notice any changes in my console output.

Here is the link for reference.

Thank you!!

<script>

// JavaScript program to implement
// the above approach

var N = 9;

// Function to check if all elements
// of the board[][] array store
// value in the range[1, 9]
function isinRange(board)
{
    
    // Traverse board[][] array
    for(var i = 0; i < N; i++)
    {
        for(var j = 0; j < N; j++)
        {
            
            // Check if board[i][j]
            // lies in the range
            if (board[i][j] <= 0 ||
                board[i][j] > 9)
            {
                return false;
            }
        }
    }
    return true;
}

// Function to check if the solution
// of sudoku puzzle is valid or not
function isValidSudoku(board)
{
    
    // Check if all elements of board[][]
    // stores value in the range[1, 9]
    if (isinRange(board) == false)
    {
        return false;
    }

    // Stores unique value
    // from 1 to N
    var unique = Array(N+1).fill(false);

    // Traverse each row of
    // the given array
    for(var i = 0; i < N; i++)
    {
        unique = Array(N+1).fill(false);

        // Traverse each column
        // of current row
        for(var j = 0; j < N; j++)
        {

            // Stores the value
            // of board[i][j]
            var Z = board[i][j];

            // Check if current row
            // stores duplicate value
            if (unique[Z])
            {
                return false;
            }
            unique[Z] = true;
        }
    }

    // Traverse each column of
    // the given array
    for(var i = 0; i < N; i++)
    {

        // Initialize unique[]
        // array to false
        unique = Array(N+1).fill(false);

        // Traverse each row
        // of current column
        for(var j = 0; j < N; j++)
        {

            // Stores the value
            // of board[j][i]
            var Z = board[j][i];

            // Check if current column
            // stores duplicate value
            if (unique[Z])
            {
                return false;
            }
            unique[Z] = true;
        }
    }

    // Traverse each block of
    // size 3 * 3 in board[][] array
    for(var i = 0; i < N - 2; i += 3) 
    {
        
        // j stores first column of
        // each 3 * 3 block
        for(var j = 0; j < N - 2; j += 3) 
        {

            // Initialize unique[]
            // array to false
            unique = Array(N+1).fill(false);

            // Traverse current block
            for(var k = 0; k < 3; k++)
            {
                for(var l = 0; l < 3; l++)
                {
                    
                    // Stores row number
                    // of current block
                    var X = i + k;

                    // Stores column number
                    // of current block
                    var Y = j + l;

                    // Stores the value
                    // of board[X][Y]
                    var Z = board[X][Y];

                    // Check if current block
                    // stores duplicate value
                    if (unique[Z])
                    {
                        return false;
                    }
                    unique[Z] = true;
                }
            }
        }
    }

    // If all conditions satisfied
    return true;
}

// Driver Code
var board = [ [ 7, 9, 2, 1, 5, 4, 3, 8, 6 ],
                [ 6, 4, 3, 8, 2, 7, 1, 5, 9 ],
                [ 8, 5, 1, 3, 9, 6, 7, 2, 4 ],
                [ 2, 6, 5, 9, 7, 3, 8, 4, 1 ],
                [ 4, 8, 9, 5, 6, 1, 2, 7, 3 ],
                [ 3, 1, 7, 4, 8, 2, 9, 6, 5 ],
                [ 1, 3, 6, 7, 4, 8, 5, 9, 2 ],
                [ 9, 7, 4, 2, 1, 5, 6, 3, 8 ],
                [ 5, 2, 8, 6, 3, 9, 4, 1, 7 ] ];
if (isValidSudoku(board))
{
    document.write("Valid");
}
else
{
    document.write("Not Valid");
}


</script>

Answer №1


In the game of Sudoku, there are smaller 3x3 blocks within the larger grid.
The code is designed to loop through each of these sub-blocks, starting with the first cell in each one.
To ensure that the code does not access cells outside of the bounds, the author included a check for N-2 condition when iterating over the sub-block cells using the variable X = i+k.
However, this condition is unnecessary when the number of columns and rows in the Sudoku grid are multiples of 3.
Removing the -2 from the condition does not make any noticeable difference in the output.

Answer №2

The reason for this pattern is that the code progresses in increments of 3

for(var i = 0; i < N - 2; i += 3)

This means i will be incremented by 3 each time

so i will be 0, 3, 6

because N = 9 -> 9-2 = 7 -> 6 is greater than 7

Further in the code, you'll notice loops k & l, which handle the 3x3 matrix

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

When the React functional component changes its state, it triggers the un-mounting and re-mounting of its parent

I created a functional component that allows for toggling the visibility of a password field using a small button that switches between closed and opened eye images. The issue I'm facing is that even though the parent does not have any affected state ...

Add an extra filter solely to a single item within the ng-repeat directive

I've been working on a project in AngularJS that involves an object with key-value pairs displayed on the page. I need all keys to have a capitalized first letter, so I applied a filter. However, if the key is 'sku', then I require all lette ...

How can you access the preloaded resolve value in AngularJS ui-router when the $stateChangeSuccess event is triggered?

$stateProvider.state('home', { url: '/', resolve: { person: function() { return 'good' } } Can you help me figure out how to access the value of 'person' in the $stateChangeSuccess callback f ...

Is there a way to retrieve the value of an input field in a batch file upload?

Greetings, I apologize if my explanation is not very clear. What I am attempting to do is retrieve the value from an input field and then display that value in a label. Below is the code snippet: Code Example I have an input field for displaying an imag ...

Trouble with React Native ListView Item Visibility

I'm currently working on integrating the React Native <ListView /> component with the <List /> and <ListItem /> components from React Native Elements. However, I seem to be facing an issue where the <ListItem /> component is no ...

Tips for sending push notifications to multiple devices via Firebase Cloud Messaging

I was exploring ways to send push messages from my expressJS server to my ionic app and I came across GCM. Using GCM, I could deliver messages by passing a list of tokens like this: sender.send(message, { registrationTokens: deviceTokens }, f ...

Leveraging string interpolation within innerHTML in an Angular application

I'm in the process of creating a game where players need to fill in blanks within dynamically generated statements. To achieve this, I require string interpolation to capture user input and dynamic innerHTML as the blanks can be positioned anywhere wi ...

What are effective strategies for safeguarding my AngularJS application code, particularly from unauthorized access through the browser's source code?

I am currently working on an AngularJS application. I have encountered a challenge where the end user is able to view the app code from the browser's source code. I am seeking advice on how to address this issue effectively. Is there any recommended ...

Managing simultaneous access to a variable in NodeJS: Best practices

For instance: var i = 0; while(true) http.request('a url', callback_f); function **callback_f**(){ **i++**; } In this straightforward scenario, multiple requests could unintentionally increase the value of i simultaneously. How can I creat ...

Tips for showcasing a restricted amount of data with Angular.js

I've been exploring different ways to limit the results using limitTo, but unfortunately, I'm encountering unexpected issues. Currently, the entire list is being displayed when I only want to show 8 key-value items in a 4/4 block format. You can ...

Locating the closest group of arrays

Can anyone suggest an algorithm to determine which array in the set below is nearest to the target [0,0,0]? My initial idea was to assign points based on the sum of each array's values. However, I realized that both index 1 [0,2,1] and index 3 have a ...

Using Angular to create a dynamic form with looping inputs that reactively responds to user

I need to implement reactive form validation for a form that has dynamic inputs created through looping data: This is what my form builder setup would be like : constructor(private formBuilder: FormBuilder) { this.userForm = this.formBuilder.group({ ...

constructing a new array instance through pushing JSON documents

There are two objects which I have defined: var id = "one"; var arrobj = Array[2] 0: Object name : "a" desc : "desc1" 1: Object name : "b" desc : "desc2" My goal is to create the object in the following structure ...

Attempting to troubleshoot and execute knex commands within the package.json file

At the moment, I am utilizing a knex project that was crafted by an individual on GitHub. I've encountered some issues with the package.json file, which should ideally simplify the execution of knex commands: { "name": "database", "version": "1. ...

Utilizing Regular Expressions in Express.js Routes

Is there a way to extract a specific value from my URL using Express? For example, my URL structure is as follows: host/:value.schema I need to retrieve the value from this URL. Here's an example: host/horse.schema (In this case, the value wo ...

jQuery event triggers upon completion of execution

A custom code has been integrated into my project using jQuery. Check out the code snippet below: <script> $("#startProgressTimer").click(function() { $("#progressTimer").progressTimer({ timeLimit: $("#restTime").val(), onFinish ...

How to Ensure that the Hidden Value of Select Statement in Angular is Always Displayed as Text

Is there a way to customize the top part of a dropdown menu so that it always displays a specific phrase, like 'Symbols' in this case, regardless of the option selected? Currently, the top part shows the last selected symbol, but I want it to be ...

` ` Despite entering correct values, the HTML form is still displaying validation errors due to JavaScript. ``

My contact form with validations is functioning well, but I am facing an issue where old errors persist even after correcting them and submitting the form again. Below is a snippet of the document containing the JavaScript code: <form id="contactForm" ...

MQTT.js experiencing issues within a Vite environment (React with TypeScript) and a Next.js application

Node version: 18.17.1 Npm version: 9.8.1 I have successfully installed the mqtt package using the following command: npm install mqtt The installation is working perfectly without any issues. Here is a snippet of the code: import { useState } from ' ...

AJAX request lacks the 'access-control-allow-origin' header

I'm currently integrating a weather API into my app to display real-time weather information. Although I've used this API before, I am now attempting to fetch the data asynchronously using AJAX to avoid full page reloads. Below is the JavaScrip ...