Skip to content

Instantly share code, notes, and snippets.

@ballpointcarrot
Created December 3, 2018 04:53
Show Gist options
  • Save ballpointcarrot/8bec8ebd2bfe8b3a0739eba824eeed1b to your computer and use it in GitHub Desktop.
Save ballpointcarrot/8bec8ebd2bfe8b3a0739eba824eeed1b to your computer and use it in GitHub Desktop.
Advent of Code 2018 - Day 2
(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))))
(defn hamming
"Compute the Hamming Distance between two equal length
strings."
[str1 str2]
(if-not (= (count str1) (count str2))
(throw (IllegalArgumentException. "Strings must be equal size.")))
(loop [s1 str1
s2 str2
score 0]
(if (empty? s1)
score
(recur (rest s1) (rest s2)
(+ score (if (= (first s1) (first s2)) 0 1))))))
(defn find-christmas-boxes [input]
(keep identity (map (fn [base-str]
(let [target-box (filter #(= 1 (hamming % base-str)) input)]
(if-not (empty? target-box)
[base-str (first target-box)]))) input)))
(defn remove-uncommon-letter [s1 s2]
(apply str (keep-indexed #(if (= (get s2 %1) %2) %2) s1)))
;; To execute everything:
;; (apply remove-uncommon-letter (first find-christmas-boxes input))
;; where input is the raw input string from the project.
(ns aoc.aoc2-test
(:require [aoc.aoc2 :as sut]
[clojure.test :refer :all]))
(deftest aoc2-part1
(testing "the example statement"
(let [input ["abcdef" "bababc"
"abbcde" "abcccd"
"aabcdd" "abcdee"
"ababab"]]
(is (= 12 (sut/checksum input)))))
(testing "a simple second example"
(let [input ["abab" "abaa" "aab"
"aac" "aaa" "abc"]]
(is (= 6 (sut/checksum input))))))
(deftest hamming
(testing "empty strings"
(is (= 0 (sut/hamming "" ""))))
(testing "errors on uneven strings"
(is (thrown? IllegalArgumentException (sut/hamming "test" "uneven"))))
(testing "distance of 1"
(is (= 1 (sut/hamming "test" "tent")))
(is (= 1 (sut/hamming "stove" "steve"))))
(testing "distance of 2"
(is (= 2 (sut/hamming "pasta" "pests")))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment