Find the difference between the sum of diagonals in a 2D matrix using JavaScript

I'm currently practicing on hackerrank and came across a challenge involving a two-dimensional matrix. Unfortunately, I encountered an error in my code implementation.

  • 11 2 4
  • 4 5 6
  • 10 8 -12

The task at hand is to calculate the sum along the primary diagonal: 11 + 5 - 12 = 4, then the secondary diagonal: 4 + 5 + 10 = 19, finally resulting in 19 - 4 = 15.

function diagonalDifference(arr) {
     var sumRight = 0;
     var sumLeft = 0;
     var array = new Array();
     for(var i = 0; i < arr.length ; i++ ){
          for(var j = 0; j < arr[i].length; j++){
               array.push(arr[i][j]);
          }
     }
     for (var i = 0 ; i < array.length; i = i + 4){
          sumRight += array[i];
     }
     for (var j = 2 ; j < array.length - 1 ; j = j + 2 ){
          sumLeft += array[j];
     }
     return sumLeft - sumRight;
}

Answer №1

give this a shot

function calculateDiagonalSums(matrix) {

    let primarySum = 0, secondarySum = 0;
    for (let row = 0; row < matrix.length; row++) {
        primarySum += matrix[row][row];
        secondarySum += matrix[row][matrix.length - row - 1];
    }
    console.log(primarySum + ' ' + secondarySum);
    console.log(primarySum - secondarySum);
}

calculateDiagonalSums([[11,2,4],[4,5,6],[10,8,-12]]);

Answer №2

It appears that your current approach may not be leading in the right direction. A more effective solution involves calculating the sum of elements from the top-left to bottom-right (referred to as sumRigth). Subsequently, calculate the sum of elements from the top-right to bottom-left (stored as sumLeft). This assumes that the arrays consist of numbers and are of equal size.

function findDiagonalDifference(matrix) {
     let sumRigth = 0, sumLeft = 0, count = 0;
     for (let i = 0 ; i < matrix.length; i++){
          sumRigth += matrix[i][count++];
     }
     count = matrix.length-1;
     for (let i = 0; i < matrix.length; i++){
          sumLeft += matrix[i][count--];
     }
     return sumLeft - sumRigth;
}

let arr = [
     [11, 2, 4],
     [4, 5, 6],
     [10, 8, -12]
];
console.log(findDiagonalDifference(arr));

Answer №3

By utilizing a single loop, it is possible to obtain two values directly to use for summation.

function calculateSum(matrix) {
    let total = 0;

    for (let i = 0, length = matrix.length; i < length; i++)
        total += matrix[i][length - i - 1] - matrix[i][i];

    return total;
}

console.log(calculateSum([[11, 2, 4], [4, 5, 6], [10, 8, -12]]));

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

Tips for utilizing [(ngModel)] with an object that is empty, null, or undefined in Angular 4

When trying to assign [(ngModel)] inside my .html code to an empty (null or undefined) object, I encountered the error message _co.object is null. There are two scenarios: one where the object has a value and one where it does not. The ngModel works fine i ...

Automated resizing for various monitor dimensions in HTML

Is there a way to dynamically adjust the zoom level on an HTML webpage based on the monitor size? For instance, an image that appears large on a laptop screen may look small on a PC monitor. Is there a solution available to scale the picture size as the mo ...

Sharing methods between controllers in AngularJS

After coming across this insightful article on Angular validation, I decided to implement it in my project. The validation is functioning perfectly, but I am struggling to access methods in other controllers upon successful form validation. Despite trying ...

Can you explain the significance of network activity groupings within the Firebug Net tab?

Can you explain the significance of different splitter lines on the Net tab in Firebug? In this screenshot, line 1 and 2 appear to be grouped together. However, line 3 stands alone. What do these groupings represent? ...

Is there a way to retrieve the hand-drawn lines at no cost in the form of a list, with each line represented as a collection of coordinates

I am currently contemplating the idea of utilizing fabric.js for an online handwriting recognition system. In order to make this system work, I need to transmit the sketched lines as a collection of lines, where each line consists of several points. If a ...

What is an example scenario where Async Storage can be tested using Jest-expo?

To better understand the testing of Mock-async-storage for reactjs, I decided to replicate an example. If you have any suggestions on a different approach to testing, please feel free to share. I attempted to mimic a use case illustrated on this stack over ...

Issues with resetting AngularJS form---"The AngularJS form

I have been putting in a lot of effort to make this work. Despite my knowledge about child scopes, prototypal inheritance, and the use of dot notation for the model, I am facing an issue with resetting the form. You can access the hosted form here. The rel ...

Efficient communication in Angular: Sharing data among controllers and components

Recently joining a new project, I am faced with the task of implementing a small feature. In my setup, there are 2 distinct views: Cars.html and Wheels.html The Cars.html view is associated with the controller Cars.controller.js On the other hand, the W ...

What is the method for applying multiple criteria to filter an array in Vuejs?

const app = new Vue({ el: '#app', data: { search: '', itemsList: [], isLoaded: false, selectNum: status, userList: [{ id: 1, name: "Prem", status: "ok" }, { id: 2, ...

Tips for dynamically loading JSON data in Pug and JavaScript by implementing scroll functionality

This is my pug file for specificBike in allBikeData .bikeshop-card.border.border-dark.bg-white.m-3.p-4 li img.shop-image.border.border-dark(src=specificBike.image, onerror="this.onerror=null; this.src=&a ...

What is the best way to position a container div over another container using Bootstrap or CSS?

https://i.sstatic.net/q1qGi.png I'm working on a Bootstrap 4 layout where container B needs to overlay part of container A. I want to achieve a design where container B appears on top of container A. Any suggestions or references on how to achieve th ...

Unexpected outcome when returning a map

Encountered a puzzling issue that requires immediate clarification. When I input the following code into my project: this.metadata = json.metadata.map((x) => {return new Metadatum(x);}); console.log(this.metadata[0].value); The output consistently sho ...

Having trouble loading CSS in an express view with a router

I am encountering an issue where I am unable to load my CSS into a view that is being rendered from a Router. The CSS loads perfectly fine for a view rendered from app.js at the root of the project directory. Below is my current directory structure, node_ ...

Struggling with adding documents into mongoDB with the help of mongoose and node.js

I have a mongoose model defined below: module.exports = mongoose.model('vbDetail', { company_name: String, rowsdata: {vals: { date: Date, transaction_type: String, transaction_num: Str ...

Step-by-step guide on dynamically adding "Input Tags" to the DOM at runtime using Selenium's JavascriptExecutor

In order to dynamically add the following element to the DOM during run time, I need assistance... <input type="text" name="imagesToAdd" value="3566"> My initial attempt was to use Selenium JavascriptExecutor for this task. However, I encounter ...

Putting Text Inside a Video Player in HTML

Is there a way to insert text, like a Logo, into my video player? I would appreciate any help on how to achieve this. Thank you. <video width="320" height="240" controls src="video/flashtrailer.mp4"> Your browser does not support the video tag. & ...

What is the correct RegEx pattern I should use to properly match the provided test case without including the ending period?

Regular Expression: /@([\S]*?(?=\s)(?!\. ))/g Given String: 'this string has @var.thing.me two strings to be @var. replaced'.replace(/@([\S]*?(?=\s)(?!\. ))/g,function(){return '7';}) Expected Result: ...

Installing a package from a private repository using a different package name with npm

I'm looking to incorporate a module from a private GitHub repository into my project. To achieve this, I will execute the command npm install git+https://[API-KEY]:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0b737c6e607 ...

What is the best way to pass a selected item from a dropdown menu as an argument when calling a function from

Is there a way to achieve the following with AngularJS?: <select> <option ng-repeat="item in items" value="item">{{item.name}}</option> </select> <a ng-click="foo(item)">Action</a> The function foo is defined in an An ...

Place an image at the top of the canvas at a specific location

Currently, I am in the process of reconstructing this specific website My approach involves working with React (similar to the aforementioned site) and utilizing the same cropper tool that they have implemented. For cropping, I am incorporating react-imag ...