Solving Hackerrank's Diagonal Difference Problem Using JavaScript

preview_player
Показать описание

To be more specific, we focus on writing a for loop with has more than one iterators.

Рекомендации по теме
Комментарии
Автор

function diagonalDifference(arr) {
let diagonal1 = 0;
let diagonal2 = 0;

for (let i = 0 ; i<arr[0].length ; i++){
diagonal1 += arr[i][i]
diagonal2 += arr[i][arr.length - i - 1]
}

return Math.abs(diagonal1 - diagonal2)

}

just find another solution that might can help, i'm just sharing for people but thank you for your video, that really inspire me to find a solution

mohfitrahgiffari
Автор

Math.abs(sum) will take care of the absolute value?

TFlies
Автор

I appreciate the help, you explained this concept very well. Keep up the videos!!

johnnathanbaxter
Автор

just found your channel searching for hacker rank solution for this problem. great explanations to the problem. Please do more solutions for hacker rank and codewars. thanks

sogggy
Автор

that's the answer I came up with, it worked

function trying(arr) {
let d1 = 0, d2 = 0;
for(let i = 0, j = arr[0].length-1; i < arr.length; i++, j--){
d1 += arr[i][i]
d2 += arr[j][i]
}
return Math.abs(d1-d2)
}

eduardopreuss
Автор

very good work don't give up and continue to publicate videos of coding

robottopgaming
Автор

Teaching pro tip - don't start by saying "it's easy" because the people looking at your video obviously didn't find it easy, and that can be discouraging.

Kgorham
Автор

How do you look at the matrix and know the position of first_diagonal_sum 'arr[i][i]' and second_diagonal_sum 'arr[i][j]' ?

Andrew-K
Автор

what if i want to add the numbers instead of subtracting

iccon
Автор

so these are 3 seperate arrays rather than just one?

Bigfaceee
Автор

Hey, I tried this solution but it's not working, my test cases are failed can you please tell me what's the reason behind it as there's not any error just simply returning 0

Gill_
Автор

why arr[0].length works?
if the arr = [9, 2, 8, 4, 3, 6, 7]
that means that you are trying to find the length of the "9"

focus_hustle-ol
Автор

I'm a beginner. It took me time, but I was able to solve it on my own. Then I came here to see if there were other simpler methods. Mine turned out to be a little shorter. U may check it out:

function diagonalDifference(arr) {
let x = 0; let y = 0;
for (let i = arr.length - 1; i >= 0; i--) {
let j = arr.length - i - 1;
x = x + arr[j][j];
y = y + arr[i][j];
}
return Math.abs(x - y)
}

s.akhtarjoomun
Автор

I'm more confused now. What the hell did I get myself into?

mugiirakimathi
Автор

Great solution, but I resolve by using “return Math.abs(first - second)”

lvchiju
Автор

I'm more confused now. What the hell did I get myself into?

mugiirakimathi
join shbcf.ru