presentation
presentation

Diagonal Difference

November 13, 2019 • ☕️ 1 min read
algorithm/hackerrank

출처

/*
 * Complete the 'diagonalDifference' function below.
 *
 * The function is expected to return an INTEGER.
 * The function accepts 2D_INTEGER_ARRAY arr as parameter.
 */

function diagonalDifference(arr) {
  const length = arr.length

  const [leftToRight, rightToLeft] = arr.reduce(
    (diagonals, row, index) => {
      diagonals[0] += row[index]
      diagonals[1] += row[length - 1 - index]

      return diagonals
    },
    [0, 0]
  )

  return Math.abs(leftToRight - rightToLeft)
}