Diagonal Difference Solution in Kotlin -HackerRank

Problem

Given a square matrix of size N x N, calculate the absolute difference between the sums of its diagonals.

Input Format

The first line contains a single integer, N. The next N lines denote the matrix’s rows, with each line containing N space-separated integers describing the columns.

Constraints

  • -100 < Elements in the matrix < 100

Output Format

Print the absolute difference between the two sums of the matrix’s diagonals as a single integer.

Sample Input

3 
11 2 4
4 5 6
10 8 -12

Sample Output

15

ANSWER


fun diagonalDifference(arr: Array<Array<Int>>): Int {
// Write your code here
var rightDiagonal = 0
var leftDiagonal = 0
for (x in 0 until arr.size) {
rightDiagonal += arr[x][arr.size-1-x]
leftDiagonal += arr[x][x]
}
return Math.abs(leftDiagonal - rightDiagonal) // integer value still positive}

Explanation

11   
5
-12

Sum across the primary diagonal: 11 + 5–12 = 4

The secondary diagonal is:

   4   
5
10

Sum across the secondary diagonal: 4 + 5 + 10 = 19

Difference: |4–19| = 15

--

--

--

Hey curious person, I am Software Developer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

https://register.legionnetwork.io/OxAPQ0aVLPA8

4 Recommendations of Arduino Types for Beginners

Uno R3 DIP Arduino

Virtualization Technologies Comparison by Veesp

How to install Proxmox hypervisor on server

Data Versioning for Efficient Workflows with MLFlow and LakeFS

Testing of Integration with 3rd-party Services Using Mock Data

Using Serializers In Your Ruby Rails App

Rancher 2.5 on your Windows 10 laptop in 5 min

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Umar Syaid Himawan

Umar Syaid Himawan

Hey curious person, I am Software Developer

More from Medium

Ideas and Solutions for Advent of Code 2021 in Kotlin — Part 3/4

RXJava Filtering Operator

Kotlin algorithms — Introduction

JDK 17 — Unsupported Class File Major Version