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

Looking for a pattern that combines Browserify and Angular?

Currently, I am embarking on a project using angular and browserify for the first time. I am seeking advice on how to properly utilize the require function with browserify. There are multiple ways to import files, but so far, I have experimented with the ...

Angular 5 with Typescript encountered a failure in webpack due to the absence of the property "data" on the Response

I am encountering an issue during webpack compilation. It compiles successfully if I remove .data, but then the page crashes with calls from template->component (which in turn calls a service). Here is the error I am facing: ERROR in src/app/components ...

FullCalendar, showcasing real-time event creation as you select dates

I am currently utilizing fullcalendar 4 on my website and I am attempting to incorporate an indicator for when a user selects a date on the calendar. While the background color changes, it's not very visible. My aim is to replicate the functionality ...

Retrieving information from a JSON object in Angular using a specific key

After receiving JSON data from the server, I currently have a variable public checkId: any = 54 How can I extract the data corresponding to ID = 54 from the provided JSON below? I am specifically looking to extract the values associated with KEY 54 " ...

Maintaining a consistent style input until it is modified

I'm currently dealing with this code (continuing from a previous question): input[type=submit]:focus { background-color: yellow; outline: none; } The issue I'm facing is that when I click anywhere else on the screen, the background color go ...

Is there a way to activate the width styling from one class to another?

I have these 2 elements in my webpage: //1st object <span class="ui-slider-handle" tabindex="0" style="left: 15.3153%;"></span> //2nd object <div id="waveform"> <wave style="display: block; position: relative; user-select: none; he ...

Updating text color with Ajax response value

I need assistance with updating the text color of a sensor value displayed using html/ajax. Currently, the sensor value is being displayed successfully, but I want the text color to change based on the value. Here's an example: if value < 50 then f ...

Prevent the browser from autofilling password information in a React Material UI textfield when it is in focus

I am currently utilizing React Material UI 4 and I am looking to disable the browser autofill/auto complete suggestion when focusing on my password field generated from `TextField`. Although it works for username and email, I am encountering issues with d ...

An unexpected page transition occurs when attempting to delete a link

I've successfully created an HTML table that dynamically adds rows and provides an option to delete the current row. Each row represents data retrieved from MongoDB, and upon clicking the delete button, I aim to delete the corresponding item from the ...

Resource Jump.js could not be loaded

Although I am still new to NPM, I have mostly built websites without using it. Recently, I decided to implement smooth scroll using Jump.js. Initially, everything seemed to work well when I used the live server extension in VScode. However, once I uploade ...

What is the best way to eliminate the [lang tag] from a URL in Next.js?

I am looking to eliminate either the /en or the /it from the URL without explicitly adding it. i18next seems to be doing it automatically, and I am unsure how to disable this behavior. I simply want it to happen in the background. https://i.stack.imgur.co ...

When attempting to declare a functional component in React utilizing styled-components in TypeScript, an error is encountered stating "No overload matches this call."

Playground https://codesandbox.io/s/typescript-type-checking-question-0b42t Sample Code type BadgeTypes = { success: string; secondary: string; alert: string; text: string; }; type Theme = { fonts?: object; borderRadius: string; primary?: o ...

Experiencing the 'Page prerendering error' message within Next.js

I encountered a prerender error during the deployment phase that I'm struggling to comprehend: Error occurred prerendering page "/about". Read more: https://nextjs.org/docs/messages/prerender-error ⨯ useSearchParams() should be wrapped in ...

What could be causing my data to shift after refreshing in Firefox with the F5 key?

My webpage has four tables, each containing rows with two text boxes filled with numeric values from the server. However, something peculiar occurs. When I add data to a row, let's say row 1, and then refresh the page, two values are mysteriously mov ...

Error: Unable to use the property 'basename' in the destructured object from 'React2.useContext(...)' because it is null

After a long break from working with React-Router, I'm diving back in with v6 for the first time. The tech stack of my application includes: Vite React Material-UI My troubleshooting steps so far have included: Searching online resources Revisiting ...

When using REACT to fetch data from an API, the absence of an 'Access-Control-Allow-Origin' header may result in access issues

I am working on a project that involves retrieving products from a company's API. After reaching out to the company, they provided me with the following information: CORS allowed origins for local development is "http://localhost:1229" To adhere t ...

JavaScript can dynamically attach EventListeners to elements, allowing for versatile and customized event

I am currently populating a table using data from an XML file. One of the columns in the table contains links to more details. Due to the unique requirements of my web page setup (Chrome extension), I need to dynamically add an event handler when the table ...

Which property is best suited for styling a phone number field in the MUI data grid in ReactJS?

I previously utilized the pattern attribute for input fields in pure HTML, but now I no longer have any input fields. What should be my next steps? Can you provide me with a reference in the MUI documentation? https://i.stack.imgur.com/ ...

There seems to be an issue with the performance of Google script .setFormula when used in conjunction with the

Hello everyone, I have written a script that inserts formulas in a specific range and set up a trigger for it to run between 01:00 and 02:00 AM. The purpose is to subscribe the values with the formulas and then paste the resulting values. However, I am fac ...

Using socket.io and express for real-time communication with WebSockets

I'm currently working on implementing socket.io with express and I utilized the express generator. However, I am facing an issue where I cannot see any logs in the console. Prior to writing this, I followed the highly upvoted solution provided by G ...