What follows are little mini problems I solved in order to finished Day 2, 2018 of The Advent of Code.
Problem 1
Identify strings that have
n
instances of any character.
Cases:
abcdef
has no repeated characters.abcdee
has 2e
.
Solution:
- Sort the input
- Partition the input by character
- Remove the partitions of incorrect length
- Are any partitions remaining?
(defn has-n-repeats? [n input]
(as-> (sort input) $
(partition-by char $)
(filter #(= n (count %)) $)
(not (empty? $))))
Problem 2
Count differences at corresponding positions between two strings.
Cases:
abcde
andfghij
differ at all five locations.fghij
andfguij
differ at one location.
Naive Solution: use set operations (union, intersection) to see how different the strings are.
Advanced Case:
xrecqmdonskvzupalfkwhjctdb
andxrlgqmavnskvzupalfiwhjctdb
differ at five positions
Solution:
In the advanced case, both strings have repeated characters, so sets aren't helpful.
Description:
- Interleave the two strings
- Partition the interleaved strings in character pairs
- remove pairs that are equal
- count the remaining pairs
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))
Problem 3:
List characters that are equal at corresponding positions between two strings (preserving order of appearance).
Cases:
fghij
andfguij
sharefgij
.
Solution:
- Interleave the two strings
- Partition the interleaved strings in character pairs
- filter for pairs that are equal
- take the first of each pair
- concatenate a string
(defn common-chars [a b]
(->> (interleave a b)
(partition 2)
(filter equal?)
(map first)
(apply str)))
Problem 4:
Among a list of strings, find the two that differ by one character at a single character position and return the common characters.
Solution:
- List comprehension of the
diff-count
between every combination of strings - Limit result where
diff-count
result is1
- Return the
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))))