(defn generate-points-from-steps
"For a vector of steps of the form [\"R\" 10] etc.,
generates a vector of points starting from origin."
[steps]
(reduce
(fn [path step]
(into []
(concat path (loc-from-loc (last path) step))))
[origin]
steps))
can be just
(reduce
(fn [path step]
(into path
(loc-from-loc (peek path) step)))
[origin]
steps)
with 2 key improvements:
1)`peek` is constant time lookup of last element in vector (`last` is linear time)
2) into
directly into path vector bypasses concat
and scans only new lock-from-loc
segment. Where concat
does not scan for concatting, but then scans entire seq: both old path
and new lock-from-lock
to put them into empty []
.so in your code - each next iteration you scan old path
segment twice: for last and after concat, instead of nonce
I think this:
(first (sort
(fn [p1 p2] (< (dist-to-origin p1) (dist-to-origin p2))
points)))
can be this:
(->> points
(sort-by dist-to-origin <)
(first))
(defn loc-from-loc
"Loc is a hash with :x and :y, step is a vector with a direction string and an integer. Returns a list of locations that have been stepped over."
[loc step]
(case (first step)
"R" (map (fn [step] (update loc :x + step)) (range 1 (+ (second step) 1)))
"L" (map (fn [step] (update loc :x - step)) (range 1 (+ (second step) 1)))
"U" (map (fn [step] (update loc :y + step)) (range 1 (+ (second step) 1)))
"D" (map (fn [step] (update loc :y - step)) (range 1 (+ (second step) 1)))))
can be shorter with destructuring:
(defn loc-from-loc
"Loc is a hash with :x and :y, step is a vector with a direction string and an integer.
Returns a list of locations that have been stepped over."
[loc [dir len]]
(let [offsets (range 1 (+ 1 len))]
(case dir
"R" (map (fn [step] (update loc :x + step)) offsets)
"L" (map (fn [step] (update loc :x - step)) offsets)
"U" (map (fn [step] (update loc :y + step)) offsets)
"D" (map (fn [step] (update loc :y - step)) offsets))))
Anyone have any tips for day 22 part 2? I think I need to revisit my algebra courses. Put possible spoilers in thread.
In noticed both the number of cards in the deck and the number of times you repeat the shuffle process are prime numbers.
I hope nobody minds me posting AoC as far back as this but after the rough start on part 1, assembling the part 2 solution from its components was a breeze.
Phew, finally solved today. Spent so much time going in wrong directions… I put the explanation in a comment https://gitlab.com/dmarjenburgh/adventofcode/blob/c7b250a5e60733fef2c6c01c5099125ef29d9c48/src/adventofcode/year_2019.clj#L732-776
thanks. i wasn't aware of modular inverse and that's why my division made the different answer..