80 lines
1.9 KiB
Janet
80 lines
1.9 KiB
Janet
# (import math)
|
|
|
|
# The smallest number in the left list is 1, and the smallest number in the
|
|
# right list is 3. The distance between them is 2.
|
|
|
|
(def test-input
|
|
[[3 4]
|
|
[4 3]
|
|
[2 5]
|
|
[1 3]
|
|
[3 9]
|
|
[3 3]])
|
|
|
|
(defn unzip [lst]
|
|
(def left @[])
|
|
(def right @[])
|
|
(each [fst snd] lst
|
|
(array/push left fst)
|
|
(array/push right snd))
|
|
[(sorted left) (sorted right)])
|
|
|
|
(def test-input-unzipped (unzip test-input))
|
|
|
|
# The second-smallest number in the left list is 2, and the second-smallest
|
|
# number in the right list is another 3. The distance between them is 1.
|
|
|
|
# The third-smallest number in both lists is 3, so the distance between them is
|
|
# 0.
|
|
|
|
# The next numbers to pair up are 3 and 4, a distance of 1.
|
|
|
|
# The fifth-smallest numbers in each list are 3 and 5, a distance of 2.
|
|
|
|
# Finally, the largest number in the left list is 4, while the largest number in
|
|
# the right list is 9; these are a distance 5 apart. To find the total distance
|
|
# between the left list and the right list, add up the distances between all of
|
|
# the pairs you found.
|
|
|
|
# In the example above, this is 2 + 1 + 0 + 1 + 2 + 5, a total distance of 11!
|
|
|
|
(defn distances [lst]
|
|
(def max-idx (min (length (lst 0))
|
|
(length (lst 1))))
|
|
(def results @[])
|
|
(for idx 0 max-idx
|
|
(def dist (math/abs (- ((lst 0) idx)
|
|
((lst 1) idx))))
|
|
(array/push results dist))
|
|
(+ ;results))
|
|
|
|
(def line-grammar
|
|
'{:main (sequence (capture :d+) :s+ (capture :d+)) })
|
|
|
|
(def handle (file/open "input"))
|
|
(def buffer @"")
|
|
(def pairs @[])
|
|
|
|
(while true
|
|
(def line (file/read handle :line))
|
|
(when (not line)
|
|
(break))
|
|
(def captures (peg/match line-grammar line))
|
|
(when captures
|
|
(def [fst snd] captures)
|
|
(array/push pairs [(scan-number fst) (scan-number snd)])))
|
|
|
|
(print
|
|
(distances (unzip pairs)))
|
|
|
|
(def [left right] (unzip pairs))
|
|
|
|
(print
|
|
(+ ;(map (fn [entry]
|
|
(def equal-to-entry?
|
|
(fn [rval]
|
|
(= rval entry)))
|
|
(* entry (count equal-to-entry? right)))
|
|
left)))
|
|
# ----
|