Problem
Given a square matrix of size N×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.
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
Code
(ns hackerrank.core
[:require [clojure.string :as s]])
(defn get-diagonal-sums-reducer
[n]
(fn
[sums [line-number line]]
(let
[primary (nth line line-number)
secondary (nth line (- n (+ 1 line-number)))]
(assoc
sums
:primary (+ primary (:primary sums))
:secondary (+ secondary (:secondary sums))))))
(let
[n (Integer/parseInt (read-line))
matrix (for
[_ (range n)]
(mapv #(Integer/parseInt %) (s/split (read-line) #"\s+")))
matrix-enumerated (map-indexed vector matrix)
sums (reduce
(get-diagonal-sums-reducer n)
{:primary 0 :secondary 0}
matrix-enumerated)
difference (- (:primary sums) (:secondary sums))]
(println (max difference (- difference))))
Couple questions in particular:
can I avoid the
get-diagonal-sums-reducersomehow? I'm only using it so that it closes overn.am I doing this as lazily as possible or is there any place I'm using vectors when seqs would have worked?
is there a much less verbose way to do this? Doesn't feel like this would be as complicated in Python.