r/adventofcode • • Dec 09 '20

SOLUTION MEGATHREAD -🎄- 2020 Day 09 Solutions -🎄-

NEW AND NOTEWORTHY

Advent of Code 2020: Gettin' Crafty With It

  • 13 days remaining until the submission deadline on December 22 at 23:59 EST
  • Full details and rules are in the Submissions Megathread

--- Day 09: Encoding Error ---


Post your solution in this megathread. Include what language(s) your solution uses! If you need a refresher, the full posting rules are detailed in the wiki under How Do The Daily Megathreads Work?.

Reminder: Top-level posts in Solution Megathreads are for code solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.

EDIT: Global leaderboard gold cap reached at 00:06:26, megathread unlocked!

41 Upvotes

995 comments sorted by

View all comments

2

u/kakaroto_BR Dec 09 '20

Clojure

(defn take-previous [start size coll]
  (->> (take (+ size start) coll) (take-last size)))

;; part 1
(defn first-number-not-sum-of-previous [preamble-size numbers]
  (->> numbers
       (take-last (- (count numbers) preamble-size))                              ; discard preamble
       (map vector (range))                                                       ; put indexes to help at take previous numbers
       (map #(vector (take-previous (first %) preamble-size numbers) (second %))) ; make a map between the number and the previous numbers
       (map #(vector (valid? (first %) (second %)) (second %)))                   ; make a map between the number and true/false if it is valid
       (filter #(nil? (first %)))                                                 ; filter non-valid numbers
       first
       second))

(defn subvecs [v]
  (let [size (inc (count v))]
    (->>
     (for [i (range 0 size) j (range i size)]
       (subvec v i j))
     (filter #(>= (count %) 2)))))

;; part 2
(defn find-encryption-weakness [numbers sum]
  (->> numbers
       subvecs
       (filter #(= sum (reduce + %)))
       first
       sort
       vector
       (apply (fn [coll] [(first coll) (last coll)]))
       (reduce +)))

1

u/daggerdragon Dec 09 '20

As per our posting guidelines in the wiki under How Do the Daily Megathreads Work?, please edit your post to put your oversized code in a paste or other external link.