What follows are little mini problems I solved in order to finished Day 2, 2018 of The Advent of Code.
Identify strings that have
n
instances of any character.
Cases:
abcdef
has no repeated characters.abcdee
has 2 e
.Solution:
(defn has-n-repeats? [n input]
(as-> (sort input) $
(partition-by char $)
(filter #(= n (count %)) $)
(not (empty? $))))
Count differences at corresponding positions between two strings.
Cases:
abcde
and fghij
differ at all five locations.fghij
and fguij
differ at one location.Naive Solution: use set operations (union, intersection) to see how different the strings are.
Advanced Case:
xrecqmdonskvzupalfkwhjctdb
and xrlgqmavnskvzupalfiwhjctdb
differ at five positionsSolution:
In the advanced case, both strings have repeated characters, so sets aren't helpful.
Description:
Data Flow for fghij
and fguij
:
(f f g g h u i i j j)
((f f) (g g) (h u) (i i) (j j))
((h u))
1
Implentation 1:
(->> (interleave a b)
(partition 2)
(remove #(= (first %) (second %)))
(count))
Implementation 2:
(->> (interleave a b)
(partition 2)
(remove #(apply = %))
(count))
Implementation 3:
(def equal? (partial apply =))
(->> (interleave a b)
(partition 2)
(remove equal?)
(count))
List characters that are equal at corresponding positions between two strings (preserving order of appearance).
Cases:
fghij
and fguij
share fgij
.Solution:
(defn common-chars [a b]
(->> (interleave a b)
(partition 2)
(filter equal?)
(map first)
(apply str)))
Among a list of strings, find the two that differ by one character at a single character position and return the common characters.
Solution:
diff-count
between every combination of stringsdiff-count
result is 1
common-chars
of that combination.(defn common-between-diff-by-one [inputs]
(first
(for [x inputs
y inputs
:when (= (diff-count x y) 1)]
(common-chars x y))))
-Michael Whatcott