Diagonal Difference Hacker Rank Kotlin My solution approves in some but fails in the rest

Asked

Viewed 32 times

-1

   fun diagonalDifference(arr: Array<Array<Int>>): Int {
     var tamanho = arr.size - 1
     var i = 0
     var diagonal1 = 0
     var diagonal2 = 0

     for(i in 0 .. tamanho){
        diagonal1 += arr[i][i]
        diagonal2 += arr[i][tamanho - i]
     }
    
     return diagonal2.minus(diagonal1)
    }

   fun main(args: Array<String>) {
     val n = readLine()!!.trim().toInt()

     val arr = Array<Array<Int>>(n, { Array<Int>(n, { 0 }) })

     for (i in 0 until n) {
        arr[i] = readLine()!!.trimEnd().split(" ").map{ it.toInt() }.toTypedArray()
     }

     val result = diagonalDifference(arr)

     println(result)
    }

In this my solution in Hacker Rank is approved in 4 cases but rejected in 6. I no longer know what to change, I am beginner and would like a help if possible.

  • Set the challenge prefix and the values they expect your program to return to (the tests you should pass)

1 answer

1


I opened here the hackerrank and I believe you missed a detail, the question asks to be returned a numero absoluto, that is, a number always positive, but depending on the input, its result can generate negative numbers if the diagonal2 is less than the diagonal1. A simple way to fix it would be by calling Math.abs. For example:

fun diagonalDifference(arr: Array<Array<Int>>): Int {
var tamanho = arr.size - 1
var i = 0
var diagonal1 = 0
var diagonal2 = 0

for(i in 0 .. tamanho){
    diagonal1 += arr[i][i]
    diagonal2 += arr[i][tamanho - i]
}

return Math.abs(diagonal2.minus(diagonal1)) //vai retornar sempre positivo agora

}
  • Po Lucas thank you very much, I no longer knew which way to run, I was thinking something in my logic was wrong. Even solved, it passed beaten that there to be only positive results.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.