DEV Community

Discussion on: AoC Day 2: Inventory Management System

Collapse
 
trueneu profile image
Pavel Gurkov • Edited

Clojure (inefficient part 2)

Part 1:

(->>
    (utils/read-file (str utils/resources-path "day2.txt"))
    (map frequencies)
    (map vals)
    (map (juxt (fn [coll] (some #(= 2 %) coll))
               (fn [coll] (some #(= 3 %) coll))))
    (reduce
      (fn [acc [_2 _3]]
        (-> acc
            (update :2 #(+ (if _2 1 0) %))
            (update :3 #(+ (if _3 1 0) %))))
      {:2 0 :3 0})
    ((fn [coll] (* (:2 coll) (:3 coll)))))

Part 2:

(->>
    (utils/read-file (str utils/resources-path "day2.txt"))
    (map #(map-indexed (fn [idx itm] [idx itm]) %))
    (map set)
    ((fn [coll] (combinatorics/combinations coll 2)))
    (map (fn [[f s]] {:diff (clj-set/difference f s) :orig [f s]}))
    (filter #(= (count (:diff %)) 1))
    ((fn [[{:keys [diff orig]}]]
       (apply str (map second (sort-by first (clj-set/difference (first orig) diff)))))))
Collapse
 
ballpointcarrot profile image
Christopher Kruse

I like the threaded use of update here in part 1 - my method used a transient map and returned a persistent copy at the end:

(ns aoc.aoc2)

(defn reduce-twos-threes
  "check the given frequency map n for twos or threes matches, and update
   the memo map to indicate if the string has a match. Used for a reducer."
  [memo n]
  (let [t-memo (transient memo)]
    (if (some (fn [[k v]] (= v 2)) n) 
      (assoc! t-memo :twos (inc (:twos t-memo))))
    (if (some (fn [[k v]] (= v 3)) n) 
      (assoc! t-memo :threes (inc (:threes t-memo))))
    (persistent! t-memo)))

(defn checksum [input]
  (let [sum-maps (map frequencies input)
        twos-threes (reduce reduce-twos-threes {:twos 0 :threes 0} sum-maps)]
    (* (:twos twos-threes) (:threes twos-threes))))
Collapse
 
trueneu profile image
Pavel Gurkov

Nice one. Is definitely faster than mine.