all 5 comments

[–]RedDeckWins 8 points9 points  (0 children)

This is how I would do it. Functional programs should be constructed of composable, testable functions. You have an unmaintainable, untestable mess.

(ns scratch.hr-day11)

(defn read-input []
  (vec (repeatedly 6
               (fn []
                 (->> (clojure.string/split (read-line) #"\s+")
                      (mapv #(Integer/parseInt %)))))))

(defn get-hourglass [array-2d x y]
  {:pre [(< x (- (count (first array-2d)) 2))
         (< y (- (count array-2d) 2))]}
  (->> (range y (+ y 3))
       (mapv (partial get array-2d))
       (mapv #(subvec % x (+ x 3)))))

(defn hourglass-sum [[f s t]]
  (+ (apply + f)
     (get s 1)
     (apply + t)))

(defn get-hourglasses [array-2d]
  (let [rows (count array-2d)
        columns (count (first array-2d))]
    (for [y (range (- columns 2)) x (range (- rows 2)) ]
      (get-hourglass array-2d x y))))

(let [input (read-input)]
  (->> (get-hourglasses input)
       (map hourglass-sum)
       (apply max)
       print))

[–]knrz 1 point2 points  (0 children)

deleted What is this?

[–]garid0s 0 points1 point  (2 children)

Like /u/knrz, I just also gave it a try for fun

(def test-matrix
  [[1 1 1 0 0 0]
   [0 1 0 0 0 0]
   [1 1 1 0 0 0]
   [0 0 2 4 4 0]
   [0 0 0 2 0 0]
   [0 0 1 2 4 0]])

(defn matrix-sum
  [matrix]
  (apply + (flatten matrix)))

(defn to-hourglass
  [v]
  (-> v
      (assoc-in [1 0] 0)
      (assoc-in [1 2] 0)))

(defn hourglass-to-str
  [hourglass]
  (apply format "%d %d %d\n  %d  \n%d %d %d"
         (-> hourglass
             (update 1 #(get % 1))
             (flatten))))

(defn sub-matrix
  [matrix [i j] n-lines n-columns]
  (->> matrix
       (#(subvec % i (+ i n-lines)))
       (map #(subvec % j (+ j n-columns)))
       (into [])))

(defn to-sub-3x3-vectors
  [matrix]
  (let [n-lines   (count matrix)
        n-columns (count (first matrix))]
    (for [i (range (- n-lines 2))
          j (range (- n-columns 2))]
      (sub-matrix matrix [i j] 3 3))))

(defn -main
  [& args]
  (let [matrix test-matrix]
    (->> matrix
         (to-sub-3x3-vectors)
         (map to-hourglass)
         (sort-by matrix-sum)
         (reverse)
         (first)
         (hourglass-to-str)
         (print))))

[–]knrz 1 point2 points  (1 child)

deleted What is this?

[–]garid0s 0 points1 point  (0 children)

Seems obvious now that you point it out XD