Viktor
Viktor

Reputation: 55

no response on stdout HackerRank Swift

Hello i practice on hackerRank using swift and now i have a problem. My code works great in swift playground, and return the expected result, but in HackerRank i have runtime error ~ no response on stdout ~ I've tried to reset code and refresh page. What could be the problem?

func diagonalDifference(arr: [[Int]]) -> Int {
    // Write your code here
   let rowNumber = arr[0][0]

    var leftD = 0
    var rightD = 0

    for i in 1...rowNumber {
        leftD += arr[i][i - 1]
    }

    var increasedNum = 0

    for i in (1...rowNumber).reversed() {
        rightD += arr[i][increasedNum]

        increasedNum += 1
    }

    var absoluteDifference = leftD - rightD

    if absoluteDifference < 0 {
        absoluteDifference = absoluteDifference * -1
    }

    return absoluteDifference
}

Here is the challenge page:

https://www.hackerrank.com/challenges/diagonal-difference/problem

Upvotes: 1

Views: 482

Answers (2)

vacawama
vacawama

Reputation: 154603

Your problem is a misunderstanding of what is passed to your diagonalDifference() function. The code which calls that function uses the first line of input to correctly size the array, but that value is not passed to your function in arr[0][0]. Instead, you should use arr.count to determine the dimensions of the array, then you should be indexing the array as 0..<arr.count.

To fix your code

change:

let rowNumber = arr[0][0]

to:

let rowNumber = arr.count

change:

leftD += arr[i][i - 1]

to:

leftD += arr[i][i]

And change both instances of

1...rowNumber

to:

0..<rowNumber

Upvotes: 1

Murat Han Acıpayam
Murat Han Acıpayam

Reputation: 1

func diagonalDifference(arr: [[Int]]) -> Int {

  var difference = 0
  for i in 0..<arr.count {
    difference += (arr[i][i] - arr[i][arr.count-1-i])
  }
  return Int(abs(difference))
}

Upvotes: 0

Related Questions