advent-of-code/2022.org
2023-06-18 20:21:18 +02:00

219 KiB
Raw Permalink Blame History

Advent Of Code 2022

Day 1: Calorie Counting

Part 1

Assignment

Santa's reindeer typically eat regular reindeer food, but they need a lot of magical energy to deliver presents on Christmas. For that, their favorite snack is a special type of star fruit that only grows deep in the jungle. The Elves have brought you on their annual expedition to the grove where the fruit grows.

To supply enough magical energy, the expedition needs to retrieve a minimum of fifty stars by December 25th. Although the Elves assure you that the grove has plenty of fruit, you decide to grab any fruit you see along the way, just in case.

Collect stars by solving puzzles. Two puzzles will be made available on each day in the Advent calendar; the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck!

The jungle must be too overgrown and difficult to navigate in vehicles or access from the air; the Elves' expedition traditionally goes on foot. As your boats approach land, the Elves begin taking inventory of their supplies. One important consideration is food - in particular, the number of Calories each Elf is carrying (your puzzle input).

The Elves take turns writing down the number of Calories contained by the various meals, snacks, rations, etc. that they've brought with them, one item per line. Each Elf separates their own inventory from the previous Elf's inventory (if any) by a blank line.

For example, suppose the Elves finish writing their items' Calories and end up with the following list:

1000 2000 3000

4000

5000 6000

7000 8000 9000

10000

This list represents the Calories of the food carried by five Elves:

The first Elf is carrying food with 1000, 2000, and 3000 Calories, a total of 6000 Calories. The second Elf is carrying one food item with 4000 Calories. The third Elf is carrying food with 5000 and 6000 Calories, a total of 11000 Calories. The fourth Elf is carrying food with 7000, 8000, and 9000 Calories, a total of 24000 Calories. The fifth Elf is carrying one food item with 10000 Calories.

In case the Elves get hungry and need extra snacks, they need to know which Elf to ask: they'd like to know how many Calories are being carried by the Elf carrying the most Calories. In the example above, this is 24000 (carried by the fourth Elf).

Find the Elf carrying the most Calories. How many total Calories is that Elf carrying?

Code

  (defun advent/1/parse-input (input)
    "Parse the INPUT string and return a list of lists."

    (let* ((lines (string-lines input))
           (elves (-non-nil (-split-on "" lines))))
      (mapcar (lambda (e) (mapcar #'string-to-number e)) elves)))

  (defun advent/1/find-elves-with-most-calories (num input)
    "Find the NUM elves in INPUT carrying the most calories."

    (let* ((parsed-input (advent/1/parse-input input))
           (elves (mapcar #'-sum parsed-input)))
      (when (<= num (length elves))
        (-sum (seq-subseq (nreverse (sort elves #'<)) 0 num)))))

Tests

  (ert-deftest advent/1/test-empty ()
    (should (equal nil (advent/1/find-elves-with-most-calories 1 ""))))

  (ert-deftest advent/1/test-empty-2 ()
    (should (equal nil (advent/1/find-elves-with-most-calories 2 ""))))

  (ert-deftest advent/1/test-newlines ()
    (should (equal nil (advent/1/find-elves-with-most-calories 1 "

  "))))

  (defconst advent/1/test-input "1000
  2000
  3000

  4000

  5000
  6000

  7000
  8000
  9000

  10000")

  (ert-deftest advent/1/test-example ()
    (should (equal 24000 (advent/1/find-elves-with-most-calories 1 advent/1/test-input))))

  (ert-deftest advent/1/test-example ()
    (should (equal 35000 (advent/1/find-elves-with-most-calories 2 advent/1/test-input))))

  (ert "advent/1/.*")

Answer

  (advent/1/find-elves-with-most-calories 1 input)
70116

Part 2

Assignment

By the time you calculate the answer to the Elves' question, they've already realized that the Elf carrying the most Calories of food might eventually run out of snacks.

To avoid this unacceptable situation, the Elves would instead like to know the total Calories carried by the top three Elves carrying the most Calories. That way, even if one of those Elves runs out of snacks, they still have two backups.

In the example above, the top three Elves are the fourth Elf (with 24000 Calories), then the third Elf (with 11000 Calories), then the fifth Elf (with 10000 Calories). The sum of the Calories carried by these three elves is 45000.

Find the top three Elves carrying the most Calories. How many Calories are those Elves carrying in total?

Answer

  (advent/1/find-elves-with-most-calories 3 input)
206582

Day 2: Rock Paper Scissors

Part 1

Assignment

The Elves begin to set up camp on the beach. To decide whose tent gets to be closest to the snack storage, a giant Rock Paper Scissors tournament is already in progress.

Rock Paper Scissors is a game between two players. Each game contains many rounds; in each round, the players each simultaneously choose one of Rock, Paper, or Scissors using a hand shape. Then, a winner for that round is selected: Rock defeats Scissors, Scissors defeats Paper, and Paper defeats Rock. If both players choose the same shape, the round instead ends in a draw.

Appreciative of your help yesterday, one Elf gives you an encrypted strategy guide (your puzzle input) that they say will be sure to help you win. "The first column is what your opponent is going to play: A for Rock, B for Paper, and C for Scissors. The second column" Suddenly, the Elf is called away to help with someone's tent.

The second column, you reason, must be what you should play in response: X for Rock, Y for Paper, and Z for Scissors. Winning every time would be suspicious, so the responses must have been carefully chosen.

The winner of the whole tournament is the player with the highest score. Your total score is the sum of your scores for each round. The score for a single round is the score for the shape you selected (1 for Rock, 2 for Paper, and 3 for Scissors) plus the score for the outcome of the round (0 if you lost, 3 if the round was a draw, and 6 if you won).

Since you can't be sure if the Elf is trying to help you or trick you, you should calculate the score you would get if you were to follow the strategy guide.

For example, suppose you were given the following strategy guide:

A Y B X C Z

This strategy guide predicts and recommends the following:

In the first round, your opponent will choose Rock (A), and you should choose Paper (Y). This ends in a win for you with a score of 8 (2 because you chose Paper + 6 because you won). In the second round, your opponent will choose Paper (B), and you should choose Rock (X). This ends in a loss for you with a score of 1 (1 + 0). The third round is a draw with both players choosing Scissors, giving you a score of 3 + 3 = 6.

In this example, if you were to follow the strategy guide, you would get a total score of 15 (8 + 1 + 6).

What would your total score be if everything goes exactly according to your strategy guide?

Code

  (defconst advent/2/values
    '((Rock . 1)
      (Paper . 2)
      (Scissors . 3)))

  (defconst advent/2/decoding
    '((A . Rock)
      (B . Paper)
      (C . Scissors)
      (X . Rock)
      (Y . Paper)
      (Z . Scissors)))

  (defun advent/2/line-value (line)
    "Evaluate the score for a single LINE in the guide.

  Each line is a list with the oppenent's choice in the car and
  your own choice in the cdr."
    (let ((own-value (alist-get (cadr line) advent/2/values 0)))
      (+ own-value
         (pcase line
           ('(Rock Rock) 3)
           ('(Rock Paper) 6)
           ('(Rock Scissors) 0)
           ('(Paper Rock) 0)
           ('(Paper Paper) 3)
           ('(Paper Scissors) 6)
           ('(Scissors Rock) 6)
           ('(Scissors Paper 0))
           ('(Scissors Scissors) 3)
           (t 0)))))

  (defun advent/2/evaluate-line (line)
    "Decode a LINE according to the interpretation and calculate its value.

  Characters that are not recognized turn into 'Invalid' symbols."
    (let ((decoded-line (mapcar
                         (lambda (e) (alist-get e advent/2/decoding 'Invalid))
                         line)))
      (advent/2/line-value decoded-line)))

  (defun advent/2/parse-guide (guide)
    "Parse the textual representation of GUIDE to a list of instructions."

    (mapcar (lambda (entry)
              (mapcar #'intern (split-string entry " ")))
            (string-lines guide)))

  (defun advent/2/evaluate-guide (guide)
    "Calculates the score of the given guide.

  (A Y)
  (B X)
  (C Z)

  The score is the sum for all lines' values in the GUIDE."

    (let ((parsed-guide (advent/2/parse-guide guide)))
      (-sum (mapcar #'advent/2/evaluate-line parsed-guide))))

Tests

  (ert-deftest advent/2/example-from-assignment ()
    (should (eql 15 (advent/2/evaluate-guide "A Y
  B X
  C Z"))))

  (ert-deftest advent/2/empty-guide-returns-zero ()
    (should (eql 0 (advent/2/evaluate-guide ""))))

  (ert-deftest advent/2/test-invalid-input ()
    (should (eql 0 (advent/2/evaluate-guide "A Q"))))

  (ert "advent/2/.*")

Answer

  (advent/2/evaluate-guide input)
14163

Part 2

Assignment

The Elf finishes helping with the tent and sneaks back over to you. "Anyway, the second column says how the round needs to end: X means you need to lose, Y means you need to end the round in a draw, and Z means you need to win. Good luck!"

The total score is still calculated in the same way, but now you need to figure out what shape to choose so the round ends as indicated. The example above now goes like this:

In the first round, your opponent will choose Rock (A), and you need the round to end in a draw (Y), so you also choose Rock. This gives you a score of 1 + 3 = 4. In the second round, your opponent will choose Paper (B), and you choose Rock so you lose (X) with a score of 1 + 0 = 1. In the third round, you will defeat your opponent's Scissors with Rock for a score of 1 + 6 = 7.

Now that you're correctly decrypting the ultra top secret strategy guide, you would get a total score of 12.

Following the Elf's instructions for the second column, what would your total score be if everything goes exactly according to your strategy guide?

Code

Interpret the guide with the new information:

  (defun advent/2/evaluate-line-2 (line)
    "Evaluate a LINE according to the second interpretation of the guide."
    (let ((opponent-move (alist-get (car line) advent/2/decoding))
          (outcome (cadr line)))
      (pcase (list opponent-move outcome)
        ('(Rock X) '(Rock Scissors))         ; lose
        ('(Rock Y) '(Rock Rock))             ; draw
        ('(Rock Z) '(Rock Paper))            ; win
        ('(Paper X) '(Paper Rock))           ; lose
        ('(Paper Y) '(Paper Paper))          ; draw
        ('(Paper Z) '(Paper Scissors))       ; win
        ('(Scissors X) '(Scissors Paper))    ; lose
        ('(Scissors Y) '(Scissors Scissors)) ; draw
        ('(Scissors Z) '(Scissors Rock))     ; win
        (_ nil))))

  (defun advent/2/evaluate-guide-2 (guide)
    "Evaluate a GUIDE but use the second interpretation instead."
    (let* ((parsed-guide (advent/2/parse-guide guide))
           (strategy (mapcar #'advent/2/evaluate-line-2 parsed-guide)))
      (-sum (mapcar #'advent/2/line-value strategy))))

Tests

  (ert-deftest advent/2/example-from-assignment-2 ()
    (should (eql 12 (advent/2/evaluate-guide-2 "A Y
  B X
  C Z"))))

Answer

  (advent/2/evaluate-guide-2 input)
12091

Day 3: Rucksack Reorganization

Part 1

Assignment

One Elf has the important job of loading all of the rucksacks with supplies for the jungle journey. Unfortunately, that Elf didn't quite follow the packing instructions, and so a few items now need to be rearranged.

Each rucksack has two large compartments. All items of a given type are meant to go into exactly one of the two compartments. The Elf that did the packing failed to follow this rule for exactly one item type per rucksack.

The Elves have made a list of all of the items currently in each rucksack (your puzzle input), but they need your help finding the errors. Every item type is identified by a single lowercase or uppercase letter (that is, a and A refer to different types of items).

The list of items for each rucksack is given as characters all on a single line. A given rucksack always has the same number of items in each of its two compartments, so the first half of the characters represent items in the first compartment, while the second half of the characters represent items in the second compartment.

For example, suppose you have the following list of contents from six rucksacks:

vJrwpWtwJgWrhcsFMMfFFhFp jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL PmmdzqPrVvPwwTWBwg wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn ttgJtRGJQctTZtZT CrZsJsPPZsGzwwsLwLmpwMDw

The first rucksack contains the items vJrwpWtwJgWrhcsFMMfFFhFp, which means its first compartment contains the items vJrwpWtwJgWr, while the second compartment contains the items hcsFMMfFFhFp. The only item type that appears in both compartments is lowercase p. The second rucksack's compartments contain jqHRNqRjqzjGDLGL and rsFMfFZSrLrFZsSL. The only item type that appears in both compartments is uppercase L. The third rucksack's compartments contain PmmdzqPrV and vPwwTWBwg; the only common item type is uppercase P. The fourth rucksack's compartments only share item type v. The fifth rucksack's compartments only share item type t. The sixth rucksack's compartments only share item type s.

To help prioritize item rearrangement, every item type can be converted to a priority:

Lowercase item types a through z have priorities 1 through 26. Uppercase item types A through Z have priorities 27 through 52.

In the above example, the priority of the item type that appears in both compartments of each rucksack is 16 (p), 38 (L), 42 (P), 22 (v), 20 (t), and 19 (s); the sum of these is 157.

Find the item type that appears in both compartments of each rucksack. What is the sum of the priorities of those item types?

Code

  (defun advent/3/split-rucksack (r)
    "Splits the rucksack content in two."

    (let ((half (/ (length r) 2)))
      (list (s-left half r) (s-right half r))))

  (defun advent/3/common-type (r)
    "Identifies the common types in a rucksack."

    (cl-destructuring-bind (first second) (advent/3/split-rucksack r)
      (-distinct (seq-intersection first second))))

  (defun advent/3/char-to-priority (c)
    "Converts a character to a priority"

    (let ((ascii-a 97)
          (ascii-A 65))
      (if (> c (- ascii-a 1))
          (- c (- ascii-a 1))
        (- c (- ascii-A 26 1)))))

  (defun advent/3/process-rucksack (r)
    (-sum (mapcar #'advent/3/char-to-priority (advent/3/common-type r))))

  (defun advent/3/process-rucksacks (rs)
    (-sum (mapcar #'advent/3/process-rucksack (string-lines (string-trim rs)))))

Tests

  (ert-deftest advent/3/test-example ()
    (should (eql
             157
             (advent/3/process-rucksacks "vJrwpWtwJgWrhcsFMMfFFhFp
  jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL
  PmmdzqPrVvPwwTWBwg
  wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn
  ttgJtRGJQctTZtZT
  CrZsJsPPZsGzwwsLwLmpwMDw"))))

  (ert-deftest advent/3/empty-rucksacks ()
    (should (eql 0 (advent/3/process-rucksacks ""))))

  (ert-deftest advent/3/single-item ()
    (should (eql 0 (advent/3/process-rucksacks "a"))))

  (ert "advent/3/.*")

Answer

  (advent/3/process-rucksacks input)
8401

Part 2

Assignment

As you finish identifying the misplaced items, the Elves come to you with another issue.

For safety, the Elves are divided into groups of three. Every Elf carries a badge that identifies their group. For efficiency, within each group of three Elves, the badge is the only item type carried by all three Elves. That is, if a group's badge is item type B, then all three Elves will have item type B somewhere in their rucksack, and at most two of the Elves will be carrying any other item type.

The problem is that someone forgot to put this year's updated authenticity sticker on the badges. All of the badges need to be pulled out of the rucksacks so the new authenticity stickers can be attached.

Additionally, nobody wrote down which item type corresponds to each group's badges. The only way to tell which item type is the right one is by finding the one item type that is common between all three Elves in each group.

Every set of three lines in your list corresponds to a single group, but each group can have a different badge item type. So, in the above example, the first group's rucksacks are the first three lines:

vJrwpWtwJgWrhcsFMMfFFhFp jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL PmmdzqPrVvPwwTWBwg

And the second group's rucksacks are the next three lines:

wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn ttgJtRGJQctTZtZT CrZsJsPPZsGzwwsLwLmpwMDw

In the first group, the only item type that appears in all three rucksacks is lowercase r; this must be their badges. In the second group, their badge item type must be Z.

Priorities for these items must still be found to organize the sticker attachment efforts: here, they are 18 (r) for the first group and 52 (Z) for the second group. The sum of these is 70.

Find the item type that corresponds to the badges of each three-Elf group. What is the sum of the priorities of those item types?

Code

  (defun advent/3/find-badge (group)
    "Find the character which appears in all elements of the GROUP.

  The single character that appears in all of them is the badge."
    (car (-distinct (-reduce #'seq-intersection group))))

  (defun advent/3/find-badges (input)
    "Sum all badge values for each group of 3 in INPUT."
    (let* ((rucksacks (string-lines (string-trim input)))
           (groups (seq-partition rucksacks 3)))
      (-sum (mapcar (-compose #'advent/3/char-to-priority #'advent/3/find-badge) groups))))

Tests

  (ert-deftest advent/3/test-example-2 ()
    (should (eql
             70
             (advent/3/find-badges "vJrwpWtwJgWrhcsFMMfFFhFp
  jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL
  PmmdzqPrVvPwwTWBwg
  wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn
  ttgJtRGJQctTZtZT
  CrZsJsPPZsGzwwsLwLmpwMDw"))))

Answer

  (advent/3/find-badges input)
2641

Day 4: Camp Cleanup

Part 1

Assignment

Space needs to be cleared before the last supplies can be unloaded from the ships, and so several Elves have been assigned the job of cleaning up sections of the camp. Every section has a unique ID number, and each Elf is assigned a range of section IDs.

However, as some of the Elves compare their section assignments with each other, they've noticed that many of the assignments overlap. To try to quickly find overlaps and reduce duplicated effort, the Elves pair up and make a big list of the section assignments for each pair (your puzzle input).

For example, consider the following list of section assignment pairs:

2-4,6-8 2-3,4-5 5-7,7-9 2-8,3-7 6-6,4-6 2-6,4-8

For the first few pairs, this list means:

Within the first pair of Elves, the first Elf was assigned sections 2-4 (sections 2, 3, and 4), while the second Elf was assigned sections 6-8 (sections 6, 7, 8). The Elves in the second pair were each assigned two sections. The Elves in the third pair were each assigned three sections: one got sections 5, 6, and 7, while the other also got 7, plus 8 and 9.

This example list uses single-digit section IDs to make it easier to draw; your actual list might contain larger numbers. Visually, these pairs of section assignments look like this:

.234….. 2-4 …..678. 6-8

.23…… 2-3 …45…. 4-5

….567.. 5-7 ……789 7-9

.2345678. 2-8 ..34567.. 3-7

…..6… 6-6 …456… 4-6

.23456… 2-6 …45678. 4-8

Some of the pairs have noticed that one of their assignments fully contains the other. For example, 2-8 fully contains 3-7, and 6-6 is fully contained by 4-6. In pairs where one assignment fully contains the other, one Elf in the pair would be exclusively cleaning sections their partner will already be cleaning, so these seem like the most in need of reconsideration. In this example, there are 2 such pairs.

In how many assignment pairs does one range fully contain the other?

Code

  (defun advent/4/pair-fully-overlaps (pair)
    (cl-destructuring-bind ((a b) (x y)) pair
      (or (and (>= a x) (<= b y))
          (and (>= x a) (<= y b)))))

  (defun advent/4/parse-input (input)
    "Parses lines with pairs.

      Example:

      2-4,6-8
      2-3,4-5
      5-7,7-9
      2-8,3-7
      6-6,4-6
      2-6,4-8"

    (let ((regex (rx (seq bos
                          (group (+ digit))
                          "-"
                          (group (+ digit))
                          ","
                          (group (+ digit))
                          "-"
                          (group (+ digit))
                          eos)))
          (lines (string-lines input)))
      (-non-nil (mapcar (lambda (line)
                          (when-let* ((string-matches (car (s-match-strings-all regex line)))
                                      (num-matches (mapcar #'string-to-number string-matches)))
                            `((,(nth 1 num-matches) ,(nth 2 num-matches))
                              (,(nth 3 num-matches) ,(nth 4 num-matches)))))
                        lines))))

  (defun advent/4/process-list (input overlap-fn)
    (let ((pairs (advent/4/parse-input input)))
      (length (-filter overlap-fn pairs))))

Tests

  (ert-deftest advent/4/test-example ()
    (should (eql 2 (advent/4/process-list "2-4,6-8
  2-3,4-5
  5-7,7-9
  2-8,3-7
  6-6,4-6
  2-6,4-8" #'advent/4/pair-fully-overlaps))))

  (ert-deftest advent/4/test-larger-digits ()
    (should (eql 2 (advent/4/process-list "20-40,60-80
  20-30,40-50
  50-70,70-90
  20-80,30-70
  60-60,40-60
  20-60,40-80" #'advent/4/pair-fully-overlaps))))

  (ert-deftest advent/4/test-invalid-input ()
    (should (eql 0 (advent/4/process-list "20-40,60-80
  20-30,40-50
  50-70,70-
  -80,30-70
  60-60 40-60
  60a-60,40-60
  20-60,40-80" #'advent/4/pair-fully-overlaps))))

  (ert-deftest advent/4/empty-list ()
    (should (eql 0 (advent/4/process-list "" #'advent/4/pair-fully-overlaps))))

  (ert "advent/4/.*")

Answer

  (advent/4/process-list input #'advent/4/pair-fully-overlaps)
448

Part 2

Assignment

It seems like there is still quite a bit of duplicate work planned. Instead, the Elves would like to know the number of pairs that overlap at all.

In the above example, the first two pairs (2-4,6-8 and 2-3,4-5) don't overlap, while the remaining four pairs (5-7,7-9, 2-8,3-7, 6-6,4-6, and 2-6,4-8) do overlap:

5-7,7-9 overlaps in a single section, 7. 2-8,3-7 overlaps all of the sections 3 through 7. 6-6,4-6 overlaps in a single section, 6. 2-6,4-8 overlaps in sections 4, 5, and 6.

So, in this example, the number of overlapping assignment pairs is 4.

In how many assignment pairs do the ranges overlap?

Code

  (defun advent/4/pair-partially-overlaps (pair)
    (cl-destructuring-bind ((a b) (x y)) pair
      (or (<= x a y)
          (<= x b y)
          (<= a x b)
          (<= a y b))))

Answer

  (advent/4/process-list input #'advent/4/pair-partially-overlaps)
794

Day 5: Supply Stacks

Part 1

Assignment

The expedition can depart as soon as the final supplies have been unloaded from the ships. Supplies are stored in stacks of marked crates, but because the needed supplies are buried under many other crates, the crates need to be rearranged.

The ship has a giant cargo crane capable of moving crates between stacks. To ensure none of the crates get crushed or fall over, the crane operator will rearrange them in a series of carefully-planned steps. After the crates are rearranged, the desired crates will be at the top of each stack.

The Elves don't want to interrupt the crane operator during this delicate procedure, but they forgot to ask her which crate will end up where, and they want to be ready to unload them as soon as possible so they can embark.

They do, however, have a drawing of the starting stacks of crates and the rearrangement procedure (your puzzle input). For example:

[D] [N] [C] [Z] [M] [P] 1 2 3

move 1 from 2 to 1 move 3 from 1 to 3 move 2 from 2 to 1 move 1 from 1 to 2

In this example, there are three stacks of crates. Stack 1 contains two crates: crate Z is on the bottom, and crate N is on top. Stack 2 contains three crates; from bottom to top, they are crates M, C, and D. Finally, stack 3 contains a single crate, P.

Then, the rearrangement procedure is given. In each step of the procedure, a quantity of crates is moved from one stack to a different stack. In the first step of the above rearrangement procedure, one crate is moved from stack 2 to stack 1, resulting in this configuration:

[D] [N] [C] [Z] [M] [P] 1 2 3

In the second step, three crates are moved from stack 1 to stack 3. Crates are moved one at a time, so the first crate to be moved (D) ends up below the second and third crates:

[Z] [N] [C] [D] [M] [P] 1 2 3

Then, both crates are moved from stack 2 to stack 1. Again, because crates are moved one at a time, crate C ends up below crate M:

[Z] [N] [M] [D] [C] [P] 1 2 3

Finally, one crate is moved from stack 1 to stack 2:

[Z] [N] [D] [C] [M] [P] 1 2 3

The Elves just need to know which crate will end up on top of each stack; in this example, the top crates are C in stack 1, M in stack 2, and Z in stack 3, so you should combine these together and give the Elves the message CMZ.

After the rearrangement procedure completes, what crate ends up on top of each stack?

Code

  (defun advent/5/read-stack-tips (stacks)
    "Read the first element of each stack of the alist of STACKS.

  All elements are concatenated to a single string."
    (let ((sorted-stacks (sort (map-keys stacks) #'<)))
      (apply #'s-concat (mapcar (lambda (key)
                                  (car (map-elt stacks key)))
                                sorted-stacks ))))

  (defun advent/5/parse-instructions (input)
    "Parse the instructions in the INPUT.

    The function returns a list of plists; one for each instruction.

    move 1 from 2 to 3

    translates to:

    ((:count 1 :from 2 :to 3))"
    (let ((regex (rx (seq
                      bol
                      "move" space
                      (group (+ digit)) space
                      "from" space
                      (group (+ digit)) space
                      "to" space
                      (group (+ digit))))))
      (-non-nil (mapcar (lambda (line)
                          (when-let ((get-number (lambda (num)
                                                   (string-to-number (match-string num line))))
                                     (match (string-match regex line)))
                            (list :count (funcall get-number 1)
                                  :from  (funcall get-number 2)
                                  :to    (funcall get-number 3))))
                        (string-lines input)))))

  (defun advent/5/parse-stacks (input)
    "Parse the plain text stack descriptions in the INPUT.

  Returns the stacks in an alist with the stack number as a key and
  a list of items as value.

  [A]
  [B] [X]

  results in:

  (1: (A B)
   2: (X))

  Each line in the stack description is split in chunks of 4
  characters. The item inside each chunk (if any) is assigned to
  the corresponding stack."
    (let* ((stacks nil)
           (regex (rx (seq "[" (group alpha) "]" (? space))))
           (lines (string-lines input)))
      (fset 'advent/5/matcher (-partial #'string-match regex))
      (dolist (line (nreverse (seq-filter #'advent/5/matcher lines)))
        (-each-indexed (seq-partition line 4)
          (lambda (index chunk)
            (when (advent/5/matcher chunk)
              (push (match-string 1 chunk)
                    (alist-get (1+ index) stacks ()))))))
      stacks))

  (defun advent/5/apply-instructions-9000 (stacks instructions)
    "Apply the INSTRUCTIONS on the STACKS.

  That is popping n items from one stack and pushing them to the
  target stack."
    (dolist (instruction instructions)
      (dotimes (i (plist-get instruction :count))
        (let ((from (plist-get instruction :from))
              (to (plist-get instruction :to)))
          (push
           (pop (alist-get from stacks))
           (alist-get to stacks)))))
    stacks)

  (defun advent/5/rearrange (arrange-fn input)
    "Read the INPUT, apply instructions according to ARRANGE-FN and return the stack tips."
    (let* ((instructions (advent/5/parse-instructions input))
           (stacks (advent/5/parse-stacks input))
           (rearranged-stacks (funcall arrange-fn stacks instructions)))
      (advent/5/read-stack-tips rearranged-stacks)))
TODO Make instruction parsing common with parser in previous assignment

Tests

  (let ((rearrange-9000 (apply-partially #'advent/5/rearrange #'advent/5/apply-instructions-9000)))

    (ert-deftest advent/5/9000/test-example ()
      (should (equal "CMZ" (funcall rearrange-9000 "    [D]
  [N] [C]
  [Z] [M] [P]
   1   2   3

  move 1 from 2 to 1
  move 3 from 1 to 3
  move 2 from 2 to 1
  move 1 from 1 to 2"))))

    (ert-deftest advent/5/9000/test-empty ()
      (should (equal "" (funcall rearrange-9000 ""))))

    (ert-deftest advent/5/9000/test-move-same ()
      (should (equal "A" (funcall rearrange-9000 "
  [A]
   1

  move 1 from 1 to 1"))))

    (ert-deftest advent/5/9000/test-move-none ()
      (should (equal "A" (funcall rearrange-9000 "
  [A]
   1

  move 0 from 2 to 1"))))

    (ert "advent/5/9000/.*"))

Answer

  (advent/5/rearrange #'advent/5/apply-instructions-9000 input)
QPJPLMNNR

Part 2

Assignment

As you watch the crane operator expertly rearrange the crates, you notice the process isn't following your prediction.

Some mud was covering the writing on the side of the crane, and you quickly wipe it away. The crane isn't a CrateMover 9000 - it's a CrateMover 9001.

The CrateMover 9001 is notable for many new and exciting features: air conditioning, leather seats, an extra cup holder, and the ability to pick up and move multiple crates at once.

Again considering the example above, the crates begin in the same configuration:

[D] [N] [C] [Z] [M] [P] 1 2 3

Moving a single crate from stack 2 to stack 1 behaves the same as before:

[D] [N] [C] [Z] [M] [P] 1 2 3

However, the action of moving three crates from stack 1 to stack 3 means that those three moved crates stay in the same order, resulting in this new configuration:

[D] [N] [C] [Z] [M] [P] 1 2 3

Next, as both crates are moved from stack 2 to stack 1, they retain their order as well:

[D] [N] [C] [Z] [M] [P] 1 2 3

Finally, a single crate is still moved from stack 1 to stack 2, but now it's crate C that gets moved:

[D] [N] [Z] [M] [C] [P] 1 2 3

In this example, the CrateMover 9001 has put the crates in a totally different order: MCD.

Before the rearrangement process finishes, update your simulation so that the Elves know where they should stand to be ready to unload the final supplies. After the rearrangement procedure completes, what crate ends up on top of each stack?

Code

  (defun advent/5/apply-instructions-9001 (stacks instructions)
    "Apply the INSTRUCTIONS on the STACKS, where multiple containers can be moved at once."

    (named-let apply-instruction ((stacks stacks)
                                  (remainder instructions))
      (if remainder
          (let* ((instruction (car remainder))
                 (count (plist-get instruction :count))
                 (from (plist-get instruction :from))
                 (to (plist-get instruction :to))
                 (from-stack (alist-get from stacks))
                 (to-stack (alist-get to stacks))
                 (new-from-stack (-drop count from-stack))
                 (moved-containers (-take count from-stack))
                 (new-to-stack (nconc moved-containers to-stack)))
            (apply-instruction (progn
                                 (setf (alist-get from stacks) new-from-stack)
                                 (setf (alist-get to stacks) new-to-stack)
                                 stacks)
                               (cdr remainder)))
        stacks)))

Tests

  (let ((rearrange-9001 (apply-partially #'advent/5/rearrange #'advent/5/apply-instructions-9001)))

    (ert-deftest advent/5/9001/test-example ()
      (should (equal "MCD" (funcall rearrange-9001 "    [D]
  [N] [C]
  [Z] [M] [P]
   1   2   3

  move 1 from 2 to 1
  move 3 from 1 to 3
  move 2 from 2 to 1
  move 1 from 1 to 2"))))

    (ert "advent/5/9001/.*"))

Answer

  (advent/5/rearrange #'advent/5/apply-instructions-9001 input)
BQDNWJPVJ

Day 6: Tuning Trouble

Part 1

Assignment

The preparations are finally complete; you and the Elves leave camp on foot and begin to make your way toward the star fruit grove.

As you move through the dense undergrowth, one of the Elves gives you a handheld device. He says that it has many fancy features, but the most important one to set up right now is the communication system.

However, because he's heard you have significant experience dealing with signal-based systems, he convinced the other Elves that it would be okay to give you their one malfunctioning device - surely you'll have no problem fixing it.

As if inspired by comedic timing, the device emits a few colorful sparks.

To be able to communicate with the Elves, the device needs to lock on to their signal. The signal is a series of seemingly-random characters that the device receives one at a time.

To fix the communication system, you need to add a subroutine to the device that detects a start-of-packet marker in the datastream. In the protocol being used by the Elves, the start of a packet is indicated by a sequence of four characters that are all different.

The device will send your subroutine a datastream buffer (your puzzle input); your subroutine needs to identify the first position where the four most recently received characters were all different. Specifically, it needs to report the number of characters from the beginning of the buffer to the end of the first such four-character marker.

For example, suppose you receive the following datastream buffer:

mjqjpqmgbljsphdztnvjfqwrcgsmlb

After the first three characters (mjq) have been received, there haven't been enough characters received yet to find the marker. The first time a marker could occur is after the fourth character is received, making the most recent four characters mjqj. Because j is repeated, this isn't a marker.

The first time a marker appears is after the seventh character arrives. Once it does, the last four characters received are jpqm, which are all different. In this case, your subroutine should report the value 7, because the first start-of-packet marker is complete after 7 characters have been processed.

Here are a few more examples:

bvwbjplbgvbhsrlpgdmjqwftvncz: first marker after character 5 nppdvjthqldpwncqszvftbrmjlhg: first marker after character 6 nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg: first marker after character 10 zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw: first marker after character 11

How many characters need to be processed before the first start-of-packet marker is detected?

Code

  (defun advent/6/unique-p (data)
    "Return t if all characters / elements in DATA are unique."
    (eql (length data) (length (seq-uniq data))))

  (defun advent/6/find-marker (data &optional window)
    (let ((window (or window 4)))
      (named-let find-marker-rec ((pos window)
                                  (remainder data))
        (when (>= (length remainder) window)
          (if (advent/6/unique-p (substring remainder 0 window))
              pos
            (find-marker-rec (1+ pos) (substring remainder 1)))))))

Tests

  (ert-deftest advent/6/4/test-example-1 ()
    (should (eql 7 (advent/6/find-marker "mjqjpqmgbljsphdztnvjfqwrcgsmlb"))))

  (ert-deftest advent/6/4/test-example-2 ()
    (should (eql 5 (advent/6/find-marker "bvwbjplbgvbhsrlpgdmjqwftvncz"))))

  (ert-deftest advent/6/4/test-example-3 ()
    (should (eql 6 (advent/6/find-marker "nppdvjthqldpwncqszvftbrmjlhg"))))

  (ert-deftest advent/6/4/test-example-4 ()
    (should (eql 10 (advent/6/find-marker "nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg"))))

  (ert-deftest advent/6/4/test-example-5 ()
    (should (eql 11 (advent/6/find-marker "zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw"))))

  (ert-deftest advent/6/4/test-example-6 ()
    (should (eql 4 (advent/6/find-marker "abcd"))))

  (ert-deftest advent/6/4/test-example-7 ()
    (should (eql 5 (advent/6/find-marker "abcad"))))

  (ert-deftest advent/6/4/test-empty ()
    (should (equal nil (advent/6/find-marker ""))))

  (ert "advent/6/4/.*")

Answer

  (advent/6/find-marker input)
1287

Part 2

Assignment

Your device's communication system is correctly detecting packets, but still isn't working. It looks like it also needs to look for messages.

A start-of-message marker is just like a start-of-packet marker, except it consists of 14 distinct characters rather than 4.

Here are the first positions of start-of-message markers for all of the above examples:

mjqjpqmgbljsphdztnvjfqwrcgsmlb: first marker after character 19 bvwbjplbgvbhsrlpgdmjqwftvncz: first marker after character 23 nppdvjthqldpwncqszvftbrmjlhg: first marker after character 23 nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg: first marker after character 29 zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw: first marker after character 26

How many characters need to be processed before the first start-of-message marker is detected?

Tests

  (let ((window 14))
    (ert-deftest advent/6/14/test-example-1 ()
      (should (eql 19 (advent/6/find-marker "mjqjpqmgbljsphdztnvjfqwrcgsmlb" window))))

    (ert-deftest advent/6/14/test-example-2 ()
      (should (eql 23 (advent/6/find-marker "bvwbjplbgvbhsrlpgdmjqwftvncz" window))))

    (ert-deftest advent/6/14/test-example-3 ()
      (should (eql 23 (advent/6/find-marker "nppdvjthqldpwncqszvftbrmjlhg" window))))

    (ert-deftest advent/6/14/test-example-4 ()
      (should (eql 29 (advent/6/find-marker "nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg" window))))

    (ert-deftest advent/6/14/test-example-5 ()
      (should (eql 26 (advent/6/find-marker "zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw" window))))

    (ert-deftest advent/6/14/test-example-6 ()
      (should (eql 4 (advent/6/find-marker "abcd" window))))

    (ert "advent/6/14/.*"))

Answer

  (advent/6/find-marker input 14)
3716

Day 7: No Space Left On Device

Part 1

Assignment

You can hear birds chirping and raindrops hitting leaves as the expedition proceeds. Occasionally, you can even hear much louder sounds in the distance; how big do the animals get out here, anyway?

The device the Elves gave you has problems with more than just its communication system. You try to run a system update:

$ system-update please pretty-please-with-sugar-on-top Error: No space left on device

Perhaps you can delete some files to make space for the update?

You browse around the filesystem to assess the situation and save the resulting terminal output (your puzzle input). For example:

$ cd / $ ls dir a 14848514 b.txt 8504156 c.dat dir d $ cd a $ ls dir e 29116 f 2557 g 62596 h.lst $ cd e $ ls 584 i $ cd .. $ cd .. $ cd d $ ls 4060174 j 8033020 d.log 5626152 d.ext 7214296 k

The filesystem consists of a tree of files (plain data) and directories (which can contain other directories or files). The outermost directory is called /. You can navigate around the filesystem, moving into or out of directories and listing the contents of the directory you're currently in.

Within the terminal output, lines that begin with $ are commands you executed, very much like some modern computers:

cd means change directory. This changes which directory is the current directory, but the specific result depends on the argument: cd x moves in one level: it looks in the current directory for the directory named x and makes it the current directory. cd .. moves out one level: it finds the directory that contains the current directory, then makes that directory the current directory. cd / switches the current directory to the outermost directory, /. ls means list. It prints out all of the files and directories immediately contained by the current directory: 123 abc means that the current directory contains a file named abc with size 123. dir xyz means that the current directory contains a directory named xyz.

Given the commands and output in the example above, you can determine that the filesystem looks visually like this:

  • / (dir)

    • a (dir)

      • e (dir)

        • i (file, size=584)
      • f (file, size=29116)
      • g (file, size=2557)
      • h.lst (file, size=62596)
    • b.txt (file, size=14848514)
    • c.dat (file, size=8504156)
    • d (dir)

      • j (file, size=4060174)
      • d.log (file, size=8033020)
      • d.ext (file, size=5626152)
      • k (file, size=7214296)

Here, there are four directories: / (the outermost directory), a and d (which are in /), and e (which is in a). These directories also contain files of various sizes.

Since the disk is full, your first step should probably be to find directories that are good candidates for deletion. To do this, you need to determine the total size of each directory. The total size of a directory is the sum of the sizes of the files it contains, directly or indirectly. (Directories themselves do not count as having any intrinsic size.)

The total sizes of the directories above can be found as follows:

The total size of directory e is 584 because it contains a single file i of size 584 and no other directories. The directory a has total size 94853 because it contains files f (size 29116), g (size 2557), and h.lst (size 62596), plus file i indirectly (a contains e which contains i). Directory d has total size 24933642. As the outermost directory, / contains every file. Its total size is 48381165, the sum of the size of every file.

To begin, find all of the directories with a total size of at most 100000, then calculate the sum of their total sizes. In the example above, these directories are a and e; the sum of their total sizes is 95437 (94853 + 584). (As in this example, this process can count files more than once!)

Find all of the directories with a total size of at most 100000. What is the sum of the total sizes of those directories?

Code

  (defun advent/7/parse-input-lines (lines)
    "Parse the list of LINES  and return an alist of files and their sizes."
    (named-let advent/7/parse-helper ((result '())
                                      (remainder lines)
                                      (curdir ""))
      (pcase (car remainder)
        ((rx "$ cd /")
         (advent/7/parse-helper result (cdr remainder) ""))
        ((rx "$ cd ..")
         (advent/7/parse-helper result (cdr remainder) (f-dirname curdir)))
        ((rx (seq bos "$ cd" (+ white) (let dir (+ (not white)))))
         (advent/7/parse-helper result (cdr remainder) (f-join curdir dir)))

        ((rx "dir")
         (advent/7/parse-helper result (cdr remainder) curdir))
        ((rx (seq bos (let size (+ digit)) white (let filename (+ (not white)))))
         (advent/7/parse-helper (map-insert result (f-join "/" curdir filename) (string-to-number size)) (cdr remainder) curdir))

        ((rx "$ ls")
         (advent/7/parse-helper result (cdr remainder) curdir))
        (_ result))))

  (defun advent/7/get-parent-directories (path)
    "List of all possible parent paths of the given file PATH.

  E.g. /a/b/c.txt will return /, /a and /a/b as parent paths."
    (let ((directories (seq-subseq (split-string path "/") 0 -1)))
      (-map-indexed (lambda (i dir)
                      (string-join (seq-subseq directories 0 (1+ i)) "/"))
                    directories)))

  (defun advent/7/directory-sizes (files-alist)
    "Report cumulative size for all directories (in)directly appearing in FILES-ALIST."
    (named-let advent/7/directory-sizes-helper ((result '())
                                                (remainder files-alist))
      (if remainder
          (let* ((file (car remainder))
                 (size (cdr file))
                 (directories (advent/7/get-parent-directories (car file))))
            (dolist (dir directories)
              (let ((stored-size (or (cdr (assoc-string dir result)) 0)))
                (setf (alist-get dir result nil nil #'string-equal) (+ stored-size size))))

            (advent/7/directory-sizes-helper result (cdr remainder)))
        result)))

  (defun advent/7/get-directories-larger-than (dir-alist max-size)
    ""
    (-filter (lambda (dir) (<= (cdr dir) max-size)) dir-alist))

  (defun advent/7/get-size-of-candidate-directories (input)
    (let* ((files (advent/7/parse-input-lines (string-lines input)))
           (directory-sizes (advent/7/directory-sizes files))
           (filtered-directories (advent/7/get-directories-larger-than directory-sizes 100000)))
      (-reduce #'+ (map-values filtered-directories))))

Tests

  (defconst advent/7/example-input "$ cd /
  $ ls
  dir a
  14848514 b.txt
  8504156 c.dat
  dir d
  $ cd a
  $ ls
  dir e
  29116 f
  2557 g
  62596 h.lst
  $ cd e
  $ ls
  584 i
  $ cd ..
  $ cd ..
  $ cd d
  $ ls
  4060174 j
  8033020 d.log
  5626152 d.ext
  7214296 k")

  (ert-deftest advent/7/1/own-example ()
    (should (eql 19 (advent/7/get-size-of-candidate-directories "$ cd /
  $ ls
  dir a
  dir b
  1 foo.txt
  2 bar.txt
  $ cd b
  $ ls
  3 baz.txt
  $ cd ..
  $ cd a
  $ ls
  5 fnord.txt"))))

  (ert-deftest advent/7/1/test-example ()
    (should (eql 95437 (advent/7/get-size-of-candidate-directories advent/7/example-input))))

  (ert-deftest advent/7/1/test-empty-dir ()
    (should (eql 0 (advent/7/get-size-of-candidate-directories "$ cd /
  $ ls
  $ cd a
  $ ls"))))

  (ert "advent/7/1/.*")

Answer

  (advent/7/get-size-of-candidate-directories input)
1432936

Part 2

Assignment

Now, you're ready to choose a directory to delete.

The total disk space available to the filesystem is 70000000. To run the update, you need unused space of at least 30000000. You need to find a directory you can delete that will free up enough space to run the update.

In the example above, the total size of the outermost directory (and thus the total amount of used space) is 48381165; this means that the size of the unused space must currently be 21618835, which isn't quite the 30000000 required by the update. Therefore, the update still requires a directory with total size of at least 8381165 to be deleted before it can run.

To achieve this, you have the following options:

Delete directory e, which would increase unused space by 584. Delete directory a, which would increase unused space by 94853. Delete directory d, which would increase unused space by 24933642. Delete directory /, which would increase unused space by 48381165.

Directories e and a are both too small; deleting them would not free up enough space. However, directories d and / are both big enough! Between these, choose the smallest: d, increasing unused space by 24933642.

Find the smallest directory that, if deleted, would free up enough space on the filesystem to run the update. What is the total size of that directory?

Code

  (defun advent/7/select-directories (input)
    (let* ((capacity 70000000)
           (required-space 30000000)
           (parsed-input (advent/7/parse-input-lines (string-lines input)))
           (directory-sizes (advent/7/directory-sizes parsed-input))
           (total-usage (alist-get "" directory-sizes))
           (free-space (- capacity total-usage))
           (to-be-freed (- required-space free-space))
           (candidates (map-filter (lambda (dir size) (>= size to-be-freed)) directory-sizes))
           (sorted-candidates (sort candidates (lambda (d1 d2) (< (cdr d1) (cdr d2))))))
      ;; get first candidate size, the smallest directory that is large enough
      (cdar sorted-candidates)))

Tests

  (ert-deftest advent/7/2/test-example ()
    (should (eql 24933642
                 (advent/7/select-directories advent/7/example-input))))

  (ert "advent/7/2/.*")

Answer

  (advent/7/select-directories input)
272298

Day 8: Treetop Tree House

Part 1

Assignment

The expedition comes across a peculiar patch of tall trees all planted carefully in a grid. The Elves explain that a previous expedition planted these trees as a reforestation effort. Now, they're curious if this would be a good location for a tree house.

First, determine whether there is enough tree cover here to keep a tree house hidden. To do this, you need to count the number of trees that are visible from outside the grid when looking directly along a row or column.

The Elves have already launched a quadcopter to generate a map with the height of each tree (your puzzle input). For example:

30373 25512 65332 33549 35390

Each tree is represented as a single digit whose value is its height, where 0 is the shortest and 9 is the tallest.

A tree is visible if all of the other trees between it and an edge of the grid are shorter than it. Only consider trees in the same row or column; that is, only look up, down, left, or right from any given tree.

All of the trees around the edge of the grid are visible - since they are already on the edge, there are no trees to block the view. In this example, that only leaves the interior nine trees to consider:

The top-left 5 is visible from the left and top. (It isn't visible from the right or bottom since other trees of height 5 are in the way.) The top-middle 5 is visible from the top and right. The top-right 1 is not visible from any direction; for it to be visible, there would need to only be trees of height 0 between it and an edge. The left-middle 5 is visible, but only from the right. The center 3 is not visible from any direction; for it to be visible, there would need to be only trees of at most height 2 between it and an edge. The right-middle 3 is visible from the right. In the bottom row, the middle 5 is visible, but the 3 and 4 are not.

With 16 trees visible on the edge and another 5 visible in the interior, a total of 21 trees are visible in this arrangement.

Consider your map; how many trees are visible from outside the grid?

Code

  (defun advent/8/height-at (hmap m n)
    "Return the height of the forest at row M column N in the given HMAP."
    (nth n (nth m hmap)))

  (defun advent/8/at-edge (hmap m n)
    "Return t if the coordinate (M,N) is at the edge of the given HMAP."
    (or (= m 0)
        (= n 0)
        (= m (1- (length hmap)))
        (= n (1- (length (car hmap))))))

  (defun advent/8/max-height-at (vmap m n direction)
    "Return the maximum height of a tree at (M,N) in a certain DIRECTION given VMAP."
    (plist-get (gethash (cons m n) vmap) direction))

  (defun advent/8/tree-is-visible (hmap m n heights)
    "Return if tree at (M,N) is visible given height map HMAP or neighboring HEIGHTS.

  A tree is visible if it is at the edge or if the tree is larger
  than all its neighbors in a certain direction."
    (or (advent/8/at-edge hmap m n)
        (-any-p (apply-partially #'> (advent/8/height-at hmap m n))
                heights)))

  (defun advent/8/update-vmap (vmap m n direction value)
    "Update the visibility map VMAP for tree at (M,N) setting a VALUE for DIRECTION."
    (let ((cur-value (gethash (cons m n) vmap)))
      (puthash (cons m n) (plist-put cur-value direction value) vmap)
      vmap))

  (defun advent/8/count-trees-from-edge ()
    '(let ((h (advent/8/height-at hmap m n))
           (vmap-update (apply-partially #'advent/8/update-vmap vmap m n))
           (max-vert (or (advent/8/max-height-at vmap (+ m (* -1 step)) n vprop) 0))
           (max-hor (or (advent/8/max-height-at vmap m (+ n (* -1 step)) hprop) 0))
           (max-heights (-non-nil (list
                                   (plist-get (gethash (cons m (1- n)) vmap) :left)
                                   (plist-get (gethash (cons m (1+ n)) vmap) :right)
                                   (plist-get (gethash (cons (1- m) n) vmap) :top)
                                   (plist-get (gethash (cons (1+ m) n) vmap) :bottom)))))
       (setq vmap (funcall vmap-update hprop (max h max-hor)))
       (setq vmap (funcall vmap-update vprop (max h max-vert)))
       (setq vmap (funcall vmap-update :visible (advent/8/tree-is-visible hmap m n max-heights)))))

  (defun advent/8/get-visibility-map (hmap process-cell-form)
    "Transforms the height map HMAP into a visibility map. Each cell is evaluated through PROCESS-CELL-FORM."
    (let ((vmap (make-hash-table :test 'equal))
          (M (length hmap))
          (N (length (car hmap))))

      (named-let update-coordinate ((m 0)
                                    (n 0)
                                    (step 1)
                                    (hprop :left)
                                    (vprop :top))
        (cond
         ;; going forward, beyond the last row; return
         ((= m M)
          (update-coordinate (1- M) (1- N) -1 :right :bottom))

         ;; going backward, beyond the first row; done
         ((= m -1)
          vmap)

         ;; going forward, beyond the last column; next row
         ((= n N)
          (update-coordinate (1+ m) 0 step hprop vprop))

         ;; going backward, beyond the first column, previous row
         ((= n -1)
          (update-coordinate (1- m) (1- N) step hprop vprop))

         ;; process a cell that's within bounds
         (t (eval process-cell-form)
            (update-coordinate m (+ n step) step hprop vprop))))))

  (defun advent/8/parse-line (line)
    (mapcar (-compose #'string-to-number #'string)
            (string-to-list line)))

  (defun advent/8/parse-input (input)
    "Parse the string representation of the map in INPUT to a matrix.

    The map is represented as a list of lists."

    (mapcar #'advent/8/parse-line (string-lines (string-trim input))))

  (defun advent/8/count-visible-trees (input)
    (let* ((hmap (advent/8/parse-input input))
           (vmap (advent/8/get-visibility-map hmap
                                              (advent/8/count-trees-from-edge))))
      (-count (lambda (cell) (plist-get cell :visible))
              (hash-table-values vmap))))

Tests

  (ert-deftest advent/8/count-1 ()
    (should (equal 8 (advent/8/count-visible-trees "789
  406
  113"))))

  (ert-deftest advent/8/count-1-newlines ()
    (should (equal 8 (advent/8/count-visible-trees "789
  406
  113
  "))))

  (ert-deftest advent/8/count-2 ()
    (should (equal 9 (advent/8/count-visible-trees "789
  416
  103"))))

  (ert-deftest advent/8/example ()
    (should (equal 21 (advent/8/count-visible-trees "30373
  25512
  65332
  33549
  35390"))))

  (ert "advent/8/.*")

Answer

  (advent/8/count-visible-trees input)
1835

Part 2

Assignment

Content with the amount of tree cover available, the Elves just need to know the best spot to build their tree house: they would like to be able to see a lot of trees.

To measure the viewing distance from a given tree, look up, down, left, and right from that tree; stop if you reach an edge or at the first tree that is the same height or taller than the tree under consideration. (If a tree is right on the edge, at least one of its viewing distances will be zero.)

The Elves don't care about distant trees taller than those found by the rules above; the proposed tree house has large eaves to keep it dry, so they wouldn't be able to see higher than the tree house anyway.

In the example above, consider the middle 5 in the second row:

30373 25512 65332 33549 35390

Looking up, its view is not blocked; it can see 1 tree (of height 3). Looking left, its view is blocked immediately; it can see only 1 tree (of height 5, right next to it). Looking right, its view is not blocked; it can see 2 trees. Looking down, its view is blocked eventually; it can see 2 trees (one of height 3, then the tree of height 5 that blocks its view).

A tree's scenic score is found by multiplying together its viewing distance in each of the four directions. For this tree, this is 4 (found by multiplying 1 * 1 * 2 * 2).

However, you can do even better: consider the tree of height 5 in the middle of the fourth row:

30373 25512 65332 33549 35390

Looking up, its view is blocked at 2 trees (by another tree with a height of 5). Looking left, its view is not blocked; it can see 2 trees. Looking down, its view is also not blocked; it can see 1 tree. Looking right, its view is blocked at 2 trees (by a massive tree of height 9).

This tree's scenic score is 8 (2 * 2 * 1 * 2); this is the ideal spot for the tree house.

Consider each tree on your map. What is the highest scenic score possible for any tree?

Code

  (defun advent/8/get-row (hmap m)
    "Return row M in HMAP."
    (nth m hmap))

  (defun advent/8/get-column (hmap n)
    "Return column N in HMAP."
    (mapcar (lambda (row) (nth n row)) hmap))

  (defun advent/8/get-visible-trees (height trees)
    "Get the number of visible TREES from the start (at HEIGHT).

  The first tree which is higher than HEIGHT is still visible, but
  everything behind it is not."
    (let ((blocked-at (-find-index (lambda (i) (>= i height)) trees)))
      (if blocked-at
          (seq-take trees (1+ blocked-at))
        trees)))

  (defun advent/8/scenic-score (hmap m n)
    "Calculates the scenic score for position (M,N) in HMAP."
    (let* ((height (advent/8/height-at hmap m n))
           (row (advent/8/get-row hmap m))
           (column (advent/8/get-column hmap n))

           ;; get the row of trees around the current tree
           (right (seq-drop row (1+ n)))
           (bottom (seq-drop column (1+ m)))
           (left (seq-take row n))
           (top (seq-take column m))

           ;; only keep visible trees from the current tree
           (right-filtered (advent/8/get-visible-trees height right))
           (bottom-filtered (advent/8/get-visible-trees height bottom))
           (left-filtered (advent/8/get-visible-trees height (reverse left)))
           (top-filtered (advent/8/get-visible-trees height (reverse top))))
      (* (length right-filtered)
         (length left-filtered)
         (length top-filtered)
         (length bottom-filtered))))

  (defun advent/8/map-hmap-scenic (hmap)
    "Iterate over each cell in HMAP to convert to its scenic score."
    (-map-indexed (lambda (m row)
                    (-map-indexed (lambda (n _)
                                    (advent/8/scenic-score hmap m n))
                                  row))
                  hmap))

  (defun advent/8/get-max-scenic-view (hmap)
    "Return the highest scenic score in the HMAP."
    (let* ((parsed-hmap (advent/8/parse-input hmap))
           (scenic-values (advent/8/map-hmap-scenic parsed-hmap)))
      (seq-max (mapcar #'seq-max scenic-values))))

Tests

  (ert-deftest advent/8/scenic-view-1 ()
    (should (equal 8 (advent/8/get-max-scenic-view "30373
  25512
  65332
  33549
  35390"))))

  (ert-deftest advent/8/scenic-view-2 ()
    (should (equal 1 (advent/8/get-max-scenic-view "11111
  11111
  11111
  11111
  11111"))))

  (ert "advent/8/scenic-view-.*")

Answer

  (advent/8/get-max-scenic-view input)
263670

Day 9: Rope Bridge

Part 1

Assignment

This rope bridge creaks as you walk along it. You aren't sure how old it is, or whether it can even support your weight.

It seems to support the Elves just fine, though. The bridge spans a gorge which was carved out by the massive river far below you.

You step carefully; as you do, the ropes stretch and twist. You decide to distract yourself by modeling rope physics; maybe you can even figure out where not to step.

Consider a rope with a knot at each end; these knots mark the head and the tail of the rope. If the head moves far enough away from the tail, the tail is pulled toward the head.

Due to nebulous reasoning involving Planck lengths, you should be able to model the positions of the knots on a two-dimensional grid. Then, by following a hypothetical series of motions (your puzzle input) for the head, you can determine how the tail will move.

Due to the aforementioned Planck lengths, the rope must be quite short; in fact, the head (H) and tail (T) must always be touching (diagonally adjacent and even overlapping both count as touching):

…. .TH. ….

…. .H.. ..T. ….

… .H. (H covers T) …

If the head is ever two steps directly up, down, left, or right from the tail, the tail must also move one step in that direction so it remains close enough:

….. ….. ….. .TH.. -> .T.H. -> ..TH. ….. ….. …..

… … … .T. .T. … .H. -> … -> .T. … .H. .H. … … …

Otherwise, if the head and tail aren't touching and aren't in the same row or column, the tail always moves one step diagonally to keep up:

….. ….. ….. ….. ..H.. ..H.. ..H.. -> ….. -> ..T.. .T… .T… ….. ….. ….. …..

….. ….. ….. ….. ….. ….. ..H.. -> …H. -> ..TH. .T… .T… ….. ….. ….. …..

You just need to work out where the tail goes as the head follows a series of motions. Assume the head and the tail both start at the same position, overlapping.

For example:

R 4 U 4 L 3 D 1 R 4 D 1 L 5 R 2

This series of motions moves the head right four steps, then up four steps, then left three steps, then down one step, and so on. After each step, you'll need to update the position of the tail if the step means the head is no longer adjacent to the tail. Visually, these motions occur as follows (s marks the starting position as a reference point):

= Initial State =

…… …… …… …… H….. (H covers T, s)

= R 4 =

…… …… …… …… TH…. (T covers s)

…… …… …… …… sTH…

…… …… …… …… s.TH..

…… …… …… …… s..TH.

= U 4 =

…… …… …… ….H. s..T..

…… …… ….H. ….T. s…..

…… ….H. ….T. …… s…..

….H. ….T. …… …… s…..

= L 3 =

…H.. ….T. …… …… s…..

..HT.. …… …… …… s…..

.HT… …… …… …… s…..

= D 1 =

..T… .H…. …… …… s…..

= R 4 =

..T… ..H… …… …… s…..

..T… …H.. …… …… s…..

…… …TH. …… …… s…..

…… ….TH …… …… s…..

= D 1 =

…… ….T. …..H …… s…..

= L 5 =

…… ….T. ….H. …… s…..

…… ….T. …H.. …… s…..

…… …… ..HT.. …… s…..

…… …… .HT… …… s…..

…… …… HT…. …… s…..

= R 2 =

…… …… .H…. (H covers T) …… s…..

…… …… .TH… …… s…..

After simulating the rope, you can count up all of the positions the tail visited at least once. In this diagram, s again marks the starting position (which the tail also visited) and # marks other positions the tail visited:

..##.. …##. .####. ….#. s###..

So, there are 13 positions the tail visited at least once.

Simulate your complete hypothetical series of motions. How many positions does the tail of the rope visit at least once?

Code

  (defun advent/9/parse-input (input)
    "Parses the string INPUT to a list of coordinate transformations."
    (-reduce #'append
             (mapcar (lambda (line)
                       (pcase line
                         ((rx (seq "L" white (let count (+ digit))))
                          (-repeat (string-to-number count) '(-1 0)))
                         ((rx (seq "R" white (let count (+ digit))))
                          (-repeat (string-to-number count) '(1 0)))
                         ((rx (seq "U" white (let count (+ digit))))
                          (-repeat (string-to-number count) '(0 -1)))
                         ((rx (seq "D" white (let count (+ digit))))
                          (-repeat (string-to-number count) '(0 1)))))
                     (string-lines input))))

  (defun advent/9/is-near (knot1 knot2)
    (cl-destructuring-bind (x1 y1) knot1
      (cl-destructuring-bind (x2 y2) knot2
        (and (<= (abs (- x1 x2)) 1)
             (<= (abs (- y1 y2)) 1)))))

  (defun advent/9/move-knot (knot1 knot2)
    "Given two knot positions, return an appropriate new position for
  KNOT2 according to KNOT1's position."
    (if (advent/9/is-near knot1 knot2)
        knot2  ; keep the old knot
      (cl-destructuring-bind (knot1-x knot1-y) knot1
        (cl-destructuring-bind (knot2-x knot2-y) knot2
          (cond
           ;; When knot2 moves diagonally, one distance is 1 and the
           ;; other is 2. For the long distance, take the middle
           ;; position on the axis, for the short distance take over the
           ;; knot1 position (essentially this is the previous knot1
           ;; position).
           ((eql (abs (- knot1-y knot2-y)) 1)
            (list (/ (+ knot1-x knot2-x) 2) knot1-y))

           ((eql (abs (- knot1-x knot2-x)) 1)
            (list knot1-x (/ (+ knot1-y knot2-y) 2)))

           ;; Take the middle position for both directions
           (t (list (/ (+ knot1-x knot2-x) 2)
                    (/ (+ knot1-y knot2-y) 2))))))))

  (defun advent/9/update-rope (rope delta)
    "Update the ROPE by moving the head with step DELTA and calculate
  all subsequent knots following head."
    (let ((new-head (-zip-with #'+ (car rope) delta)))
      (named-let update-knot ((knots (cdr rope))
                              (new-rope (list new-head)))
        (if knots
            (update-knot (cdr knots) (append new-rope (list (advent/9/move-knot (car (last new-rope)) (car knots)))))
          new-rope))))

  (defun advent/9/execute-instructions (instructions rope-length)
    (named-let advent/9/execute-instruction
        ((remainder instructions)
         (rope (-repeat rope-length '(0 0)))
         (tail-positions '((0 0))))

      (if-let* ((delta (car remainder))
                (new-rope (advent/9/update-rope rope delta)))
          (advent/9/execute-instruction (cdr remainder)
                                        new-rope
                                        (add-to-list 'tail-positions (car (last new-rope))))

        ;; no instructions left, return collected tail positions
        (length tail-positions))))

  (defun advent/9/get-tail-position-count (input &optional rope-length)
    (let* ((parsed-input (advent/9/parse-input input)))
      (advent/9/execute-instructions parsed-input
                                     (or rope-length 2))))

Tests

  (ert-deftest advent/9/1/straight-left-1 ()
    (should (equal 1 (advent/9/get-tail-position-count "L 1"))))

  (ert-deftest advent/9/1/straight-left-3 ()
    (should (equal 3 (advent/9/get-tail-position-count "L 3"))))

  (ert-deftest advent/9/1/straight-right-1 ()
    (should (equal 1 (advent/9/get-tail-position-count "R 1"))))

  (ert-deftest advent/9/1/straight-right-3 ()
    (should (equal 3 (advent/9/get-tail-position-count "R 3"))))

  (ert-deftest advent/9/1/straight-up-1 ()
    (should (equal 1 (advent/9/get-tail-position-count "U 1"))))

  (ert-deftest advent/9/1/straight-up-3 ()
    (should (equal 3 (advent/9/get-tail-position-count "U 3"))))

  (ert-deftest advent/9/1/straight-down-1 ()
    (should (equal 1 (advent/9/get-tail-position-count "D 1"))))

  (ert-deftest advent/9/1/straight-down-3 ()
    (should (equal 3 (advent/9/get-tail-position-count "D 3"))))

  (ert-deftest advent/9/1/straight-diagonal-1 ()
    (should (equal 1 (advent/9/get-tail-position-count "U 1
  R 1"))))

  (ert-deftest advent/9/1/diagonal-LU-1 ()
    (should (equal 2 (advent/9/get-tail-position-count "L 1
  U 2"))))

  (ert-deftest advent/9/1/diagonal-RU-1 ()
    (should (equal 2 (advent/9/get-tail-position-count "R 1
  U 2"))))

  (ert-deftest advent/9/1/diagonal-LD-1 ()
    (should (equal 2 (advent/9/get-tail-position-count "L 1
  D 2"))))

  (ert-deftest advent/9/1/diagonal-RD-1 ()
    (should (equal 2 (advent/9/get-tail-position-count "R 1
  D 2"))))

  (ert-deftest advent/9/1/example-1 ()
    (should (equal 13 (advent/9/get-tail-position-count "R 4
  U 4
  L 3
  D 1
  R 4
  D 1
  L 5
  R 2"))))

  (ert "advent/9/1/.*")

Answer

  (advent/9/get-tail-position-count input)
6175

Part 2

Assignment

The ropes are moving too quickly to grab; you only have a few seconds to choose how to arch your body to avoid being hit. Fortunately, your simulation can be extended to support longer ropes.

Rather than two knots, you now must simulate a rope consisting of ten knots. One knot is still the head of the rope and moves according to the series of motions. Each knot further down the rope follows the knot in front of it using the same rules as before.

Using the same series of motions as the above example, but with the knots marked H, 1, 2, …, 9, the motions now occur as follows:

= Initial State =

…… …… …… …… H….. (H covers 1, 2, 3, 4, 5, 6, 7, 8, 9, s)

= R 4 =

…… …… …… …… 1H…. (1 covers 2, 3, 4, 5, 6, 7, 8, 9, s)

…… …… …… …… 21H… (2 covers 3, 4, 5, 6, 7, 8, 9, s)

…… …… …… …… 321H.. (3 covers 4, 5, 6, 7, 8, 9, s)

…… …… …… …… 4321H. (4 covers 5, 6, 7, 8, 9, s)

= U 4 =

…… …… …… ….H. 4321.. (4 covers 5, 6, 7, 8, 9, s)

…… …… ….H. .4321. 5….. (5 covers 6, 7, 8, 9, s)

…… ….H. ….1. .432.. 5….. (5 covers 6, 7, 8, 9, s)

….H. ….1. ..432. .5…. 6….. (6 covers 7, 8, 9, s)

= L 3 =

…H.. ….1. ..432. .5…. 6….. (6 covers 7, 8, 9, s)

..H1.. …2.. ..43.. .5…. 6….. (6 covers 7, 8, 9, s)

.H1… …2.. ..43.. .5…. 6….. (6 covers 7, 8, 9, s)

= D 1 =

..1… .H.2.. ..43.. .5…. 6….. (6 covers 7, 8, 9, s)

= R 4 =

..1… ..H2.. ..43.. .5…. 6….. (6 covers 7, 8, 9, s)

..1… …H.. (H covers 2) ..43.. .5…. 6….. (6 covers 7, 8, 9, s)

…… …1H. (1 covers 2) ..43.. .5…. 6….. (6 covers 7, 8, 9, s)

…… …21H ..43.. .5…. 6….. (6 covers 7, 8, 9, s)

= D 1 =

…… …21. ..43.H .5…. 6….. (6 covers 7, 8, 9, s)

= L 5 =

…… …21. ..43H. .5…. 6….. (6 covers 7, 8, 9, s)

…… …21. ..4H.. (H covers 3) .5…. 6….. (6 covers 7, 8, 9, s)

…… …2.. ..H1.. (H covers 4; 1 covers 3) .5…. 6….. (6 covers 7, 8, 9, s)

…… …2.. .H13.. (1 covers 4) .5…. 6….. (6 covers 7, 8, 9, s)

…… …… H123.. (2 covers 4) .5…. 6….. (6 covers 7, 8, 9, s)

= R 2 =

…… …… .H23.. (H covers 1; 2 covers 4) .5…. 6….. (6 covers 7, 8, 9, s)

…… …… .1H3.. (H covers 2, 4) .5…. 6….. (6 covers 7, 8, 9, s)

Now, you need to keep track of the positions the new tail, 9, visits. In this example, the tail never moves, and so it only visits 1 position. However, be careful: more types of motion are possible than before, so you might want to visually compare your simulated rope to the one above.

Here's a larger example:

R 5 U 8 L 8 D 3 R 17 D 10 L 25 U 20

These motions occur as follows (individual steps are not shown):

= Initial State =

…………………….. …………………….. …………………….. …………………….. …………………….. …………………….. …………………….. …………………….. …………………….. …………………….. …………………….. …………………….. …………………….. …………………….. …………………….. ………..H………….. (H covers 1, 2, 3, 4, 5, 6, 7, 8, 9, s) …………………….. …………………….. …………………….. …………………….. ……………………..

= R 5 =

…………………….. …………………….. …………………….. …………………….. …………………….. …………………….. …………………….. …………………….. …………………….. …………………….. …………………….. …………………….. …………………….. …………………….. …………………….. ………..54321H……… (5 covers 6, 7, 8, 9, s) …………………….. …………………….. …………………….. …………………….. ……………………..

= U 8 =

…………………….. …………………….. …………………….. …………………….. …………………….. …………………….. …………………….. …………….H……… …………….1……… …………….2……… …………….3……… ……………54……… …………..6……….. ………….7………… …………8…………. ………..9………….. (9 covers s) …………………….. …………………….. …………………….. …………………….. ……………………..

= L 8 =

…………………….. …………………….. …………………….. …………………….. …………………….. …………………….. …………………….. ……..H1234…………. …………5…………. …………6…………. …………7…………. …………8…………. …………9…………. …………………….. …………………….. ………..s………….. …………………….. …………………….. …………………….. …………………….. ……………………..

= D 3 =

…………………….. …………………….. …………………….. …………………….. …………………….. …………………….. …………………….. …………………….. ………2345…………. ……..1…6…………. ……..H…7…………. …………8…………. …………9…………. …………………….. …………………….. ………..s………….. …………………….. …………………….. …………………….. …………………….. ……………………..

= R 17 =

…………………….. …………………….. …………………….. …………………….. …………………….. …………………….. …………………….. …………………….. …………………….. …………………….. …………….987654321H …………………….. …………………….. …………………….. …………………….. ………..s………….. …………………….. …………………….. …………………….. …………………….. ……………………..

= D 10 =

…………………….. …………………….. …………………….. …………………….. …………………….. …………………….. …………………….. …………………….. …………………….. …………………….. …………………….. …………………….. …………………….. …………………….. …………………….. ………..s………98765 …………………….4 …………………….3 …………………….2 …………………….1 …………………….H

= L 25 =

…………………….. …………………….. …………………….. …………………….. …………………….. …………………….. …………………….. …………………….. …………………….. …………………….. …………………….. …………………….. …………………….. …………………….. …………………….. ………..s………….. …………………….. …………………….. …………………….. …………………….. H123456789…………….

= U 20 =

H……………………. 1……………………. 2……………………. 3……………………. 4……………………. 5……………………. 6……………………. 7……………………. 8……………………. 9……………………. …………………….. …………………….. …………………….. …………………….. …………………….. ………..s………….. …………………….. …………………….. …………………….. …………………….. ……………………..

Now, the tail (9) visits 36 positions (including s) at least once:

…………………….. …………………….. …………………….. …………………….. …………………….. …………………….. …………………….. …………………….. …………………….. #……………………. #………….###……… #…………#…#…….. .#……….#…..#……. ..#……….#…..#…… …#……..#…….#….. ….#……s………#…. …..#…………..#….. ……#…………#…… …….#……….#……. ……..#……..#…….. ………########………

Simulate your complete series of motions on a larger rope with ten knots. How many positions does the tail of the rope visit at least once?

Tests

  (ert-deftest advent/9/2/example-1 ()
    (should (equal 1 (advent/9/get-tail-position-count "R 4
  U 4
  L 3
  D 1
  R 4
  D 1
  L 5
  R 2" 10))))

  (ert-deftest advent/9/2/example-2 ()
    (should (equal 36 (advent/9/get-tail-position-count "R 5
  U 8
  L 8
  D 3
  R 17
  D 10
  L 25
  U 20" 10))))

  (ert "advent/9/2/.*")

Answer

  (advent/9/get-tail-position-count input 10)
2578

Day 10: Cathode-Ray Tube

Part 1

Assignment

You avoid the ropes, plunge into the river, and swim to shore.

The Elves yell something about meeting back up with them upriver, but the river is too loud to tell exactly what they're saying. They finish crossing the bridge and disappear from view.

Situations like this must be why the Elves prioritized getting the communication system on your handheld device working. You pull it out of your pack, but the amount of water slowly draining from a big crack in its screen tells you it probably won't be of much immediate use.

Unless, that is, you can design a replacement for the device's video system! It seems to be some kind of cathode-ray tube screen and simple CPU that are both driven by a precise clock circuit. The clock circuit ticks at a constant rate; each tick is called a cycle.

Start by figuring out the signal being sent by the CPU. The CPU has a single register, X, which starts with the value 1. It supports only two instructions:

addx V takes two cycles to complete. After two cycles, the X register is increased by the value V. (V can be negative.) noop takes one cycle to complete. It has no other effect.

The CPU uses these instructions in a program (your puzzle input) to, somehow, tell the screen what to draw.

Consider the following small program:

noop addx 3 addx -5

Execution of this program proceeds as follows:

At the start of the first cycle, the noop instruction begins execution. During the first cycle, X is 1. After the first cycle, the noop instruction finishes execution, doing nothing. At the start of the second cycle, the addx 3 instruction begins execution. During the second cycle, X is still 1. During the third cycle, X is still 1. After the third cycle, the addx 3 instruction finishes execution, setting X to 4. At the start of the fourth cycle, the addx -5 instruction begins execution. During the fourth cycle, X is still 4. During the fifth cycle, X is still 4. After the fifth cycle, the addx -5 instruction finishes execution, setting X to -1.

Maybe you can learn something by looking at the value of the X register throughout execution. For now, consider the signal strength (the cycle number multiplied by the value of the X register) during the 20th cycle and every 40 cycles after that (that is, during the 20th, 60th, 100th, 140th, 180th, and 220th cycles).

For example, consider this larger program:

addx 15 addx -11 addx 6 addx -3 addx 5 addx -1 addx -8 addx 13 addx 4 noop addx -1 addx 5 addx -1 addx 5 addx -1 addx 5 addx -1 addx 5 addx -1 addx -35 addx 1 addx 24 addx -19 addx 1 addx 16 addx -11 noop noop addx 21 addx -15 noop noop addx -3 addx 9 addx 1 addx -3 addx 8 addx 1 addx 5 noop noop noop noop noop addx -36 noop addx 1 addx 7 noop noop noop addx 2 addx 6 noop noop noop noop noop addx 1 noop noop addx 7 addx 1 noop addx -13 addx 13 addx 7 noop addx 1 addx -33 noop noop noop addx 2 noop noop noop addx 8 noop addx -1 addx 2 addx 1 noop addx 17 addx -9 addx 1 addx 1 addx -3 addx 11 noop noop addx 1 noop addx 1 noop noop addx -13 addx -19 addx 1 addx 3 addx 26 addx -30 addx 12 addx -1 addx 3 addx 1 noop noop noop addx -9 addx 18 addx 1 addx 2 noop noop addx 9 noop noop noop addx -1 addx 2 addx -37 addx 1 addx 3 noop addx 15 addx -21 addx 22 addx -6 addx 1 noop addx 2 addx 1 noop addx -10 noop noop addx 20 addx 1 addx 2 addx 2 addx -6 addx -11 noop noop noop

The interesting signal strengths can be determined as follows:

During the 20th cycle, register X has the value 21, so the signal strength is 20 * 21 = 420. (The 20th cycle occurs in the middle of the second addx -1, so the value of register X is the starting value, 1, plus all of the other addx values up to that point: 1 + 15 - 11 + 6 - 3 + 5 - 1 - 8 + 13 + 4 = 21.) During the 60th cycle, register X has the value 19, so the signal strength is 60 * 19 = 1140. During the 100th cycle, register X has the value 18, so the signal strength is 100 * 18 = 1800. During the 140th cycle, register X has the value 21, so the signal strength is 140 * 21 = 2940. During the 180th cycle, register X has the value 16, so the signal strength is 180 * 16 = 2880. During the 220th cycle, register X has the value 18, so the signal strength is 220 * 18 = 3960.

The sum of these signal strengths is 13140.

Find the signal strength during the 20th, 60th, 100th, 140th, 180th, and 220th cycles. What is the sum of these six signal strengths?

Code

  (defun advent/10/parse-input (input)
    "Converts the instructions to a list of numbers that should be
    added to the running value of x."
    (append '(0)
            (-reduce #'append
                     (mapcar (lambda (line)
                               (pcase line
                                 ((rx "noop") '(0)
                                  )
                                 ((rx (seq "addx" white (let delta (seq (? "-") (+ digit)))))
                                  (list 0 (string-to-number delta)))))
                             (string-lines input)))))

  (defun advent/10/get-signal-strength (input &optional _positions)
    "Calculates the signal strength by summing the product of
    position and x value for each given position."
    (let ((positions (or _positions '(20 60 100 140 180 220)))
          (processed-signals (advent/10/evaluate-x input)))
      (-reduce #'+
               (mapcar (lambda (pos) (* pos
                                   (or (elt processed-signals (- pos 1)) 0)))
                       positions))))

  (defun advent/10/evaluate-x (input)
    "Given instructions in INPUT, return a list of mutations of X."
    (named-let update-signal ((remainder (advent/10/parse-input input))
                              (x 1)
                              (processed-signals nil))
      (if remainder
          (let ((new-x (+ x (car remainder))))
            (update-signal (cdr remainder) new-x (append processed-signals (list new-x))))
        processed-signals)))

Tests

  (ert-deftest advent/10/1/example-1 ()
    (should (equal 23 (advent/10/get-signal-strength "noop
  addx 3
  addx -5" '(3 5)))))

  (defvar advent/10/example "addx 15
  addx -11
  addx 6
  addx -3
  addx 5
  addx -1
  addx -8
  addx 13
  addx 4
  noop
  addx -1
  addx 5
  addx -1
  addx 5
  addx -1
  addx 5
  addx -1
  addx 5
  addx -1
  addx -35
  addx 1
  addx 24
  addx -19
  addx 1
  addx 16
  addx -11
  noop
  noop
  addx 21
  addx -15
  noop
  noop
  addx -3
  addx 9
  addx 1
  addx -3
  addx 8
  addx 1
  addx 5
  noop
  noop
  noop
  noop
  noop
  addx -36
  noop
  addx 1
  addx 7
  noop
  noop
  noop
  addx 2
  addx 6
  noop
  noop
  noop
  noop
  noop
  addx 1
  noop
  noop
  addx 7
  addx 1
  noop
  addx -13
  addx 13
  addx 7
  noop
  addx 1
  addx -33
  noop
  noop
  noop
  addx 2
  noop
  noop
  noop
  addx 8
  noop
  addx -1
  addx 2
  addx 1
  noop
  addx 17
  addx -9
  addx 1
  addx 1
  addx -3
  addx 11
  noop
  noop
  addx 1
  noop
  addx 1
  noop
  noop
  addx -13
  addx -19
  addx 1
  addx 3
  addx 26
  addx -30
  addx 12
  addx -1
  addx 3
  addx 1
  noop
  noop
  noop
  addx -9
  addx 18
  addx 1
  addx 2
  noop
  noop
  addx 9
  noop
  noop
  noop
  addx -1
  addx 2
  addx -37
  addx 1
  addx 3
  noop
  addx 15
  addx -21
  addx 22
  addx -6
  addx 1
  noop
  addx 2
  addx 1
  noop
  addx -10
  noop
  noop
  addx 20
  addx 1
  addx 2
  addx 2
  addx -6
  addx -11
  noop
  noop
  noop")

  (ert-deftest advent/10/1/example-2 ()
    (should (equal 13140 (advent/10/get-signal-strength advent/10/example))))

  (ert "advent/10/1/.*")

Answer

  (advent/10/get-signal-strength input)
13820

Part 2

Assignment

It seems like the X register controls the horizontal position of a sprite. Specifically, the sprite is 3 pixels wide, and the X register sets the horizontal position of the middle of that sprite. (In this system, there is no such thing as "vertical position": if the sprite's horizontal position puts its pixels where the CRT is currently drawing, then those pixels will be drawn.)

You count the pixels on the CRT: 40 wide and 6 high. This CRT screen draws the top row of pixels left-to-right, then the row below that, and so on. The left-most pixel in each row is in position 0, and the right-most pixel in each row is in position 39.

Like the CPU, the CRT is tied closely to the clock circuit: the CRT draws a single pixel during each cycle. Representing each pixel of the screen as a #, here are the cycles during which the first and last pixel in each row are drawn:

Cycle 1 -> ######################################## <- Cycle 40 Cycle 41 -> ######################################## <- Cycle 80 Cycle 81 -> ######################################## <- Cycle 120 Cycle 121 -> ######################################## <- Cycle 160 Cycle 161 -> ######################################## <- Cycle 200 Cycle 201 -> ######################################## <- Cycle 240

So, by carefully timing the CPU instructions and the CRT drawing operations, you should be able to determine whether the sprite is visible the instant each pixel is drawn. If the sprite is positioned such that one of its three pixels is the pixel currently being drawn, the screen produces a lit pixel (#); otherwise, the screen leaves the pixel dark (.).

The first few pixels from the larger example above are drawn as follows:

Sprite position: ###……………………………….

Start cycle 1: begin executing addx 15 During cycle 1: CRT draws pixel in position 0 Current CRT row: #

During cycle 2: CRT draws pixel in position 1 Current CRT row: ## End of cycle 2: finish executing addx 15 (Register X is now 16) Sprite position: ……………###………………….

Start cycle 3: begin executing addx -11 During cycle 3: CRT draws pixel in position 2 Current CRT row: ##.

During cycle 4: CRT draws pixel in position 3 Current CRT row: ##.. End of cycle 4: finish executing addx -11 (Register X is now 5) Sprite position: ….###……………………………

Start cycle 5: begin executing addx 6 During cycle 5: CRT draws pixel in position 4 Current CRT row: ##..#

During cycle 6: CRT draws pixel in position 5 Current CRT row: ##..## End of cycle 6: finish executing addx 6 (Register X is now 11) Sprite position: ……….###………………………

Start cycle 7: begin executing addx -3 During cycle 7: CRT draws pixel in position 6 Current CRT row: ##..##.

During cycle 8: CRT draws pixel in position 7 Current CRT row: ##..##.. End of cycle 8: finish executing addx -3 (Register X is now 8) Sprite position: …….###…………………………

Start cycle 9: begin executing addx 5 During cycle 9: CRT draws pixel in position 8 Current CRT row: ##..##..#

During cycle 10: CRT draws pixel in position 9 Current CRT row: ##..##..## End of cycle 10: finish executing addx 5 (Register X is now 13) Sprite position: …………###…………………….

Start cycle 11: begin executing addx -1 During cycle 11: CRT draws pixel in position 10 Current CRT row: ##..##..##.

During cycle 12: CRT draws pixel in position 11 Current CRT row: ##..##..##.. End of cycle 12: finish executing addx -1 (Register X is now 12) Sprite position: ………..###……………………..

Start cycle 13: begin executing addx -8 During cycle 13: CRT draws pixel in position 12 Current CRT row: ##..##..##..#

During cycle 14: CRT draws pixel in position 13 Current CRT row: ##..##..##..## End of cycle 14: finish executing addx -8 (Register X is now 4) Sprite position: …###…………………………….

Start cycle 15: begin executing addx 13 During cycle 15: CRT draws pixel in position 14 Current CRT row: ##..##..##..##.

During cycle 16: CRT draws pixel in position 15 Current CRT row: ##..##..##..##.. End of cycle 16: finish executing addx 13 (Register X is now 17) Sprite position: …………….###…………………

Start cycle 17: begin executing addx 4 During cycle 17: CRT draws pixel in position 16 Current CRT row: ##..##..##..##..#

During cycle 18: CRT draws pixel in position 17 Current CRT row: ##..##..##..##..## End of cycle 18: finish executing addx 4 (Register X is now 21) Sprite position: ………………..###……………..

Start cycle 19: begin executing noop During cycle 19: CRT draws pixel in position 18 Current CRT row: ##..##..##..##..##. End of cycle 19: finish executing noop

Start cycle 20: begin executing addx -1 During cycle 20: CRT draws pixel in position 19 Current CRT row: ##..##..##..##..##..

During cycle 21: CRT draws pixel in position 20 Current CRT row: ##..##..##..##..##..# End of cycle 21: finish executing addx -1 (Register X is now 20) Sprite position: ……………….###………………

Allowing the program to run to completion causes the CRT to produce the following image:

##..##..##..##..##..##..##..##..##..##.. ###…###…###…###…###…###…###. ####….####….####….####….####…. #####…..#####…..#####…..#####….. ######……######……######……#### #######…….#######…….#######…..

Render the image given by your program. What eight capital letters appear on your CRT?

Code

  (defun advent/10/draw-screen (input)
    "Draws the screen according to the x value specified by the INPUT.

  First all screen positions are filled according to the current
  sprite specified by the current x value. Then the sequence of
  positions is split according to the screen dimensions."
    (let* ((processed-input (advent/10/evaluate-x input))
           (screen-height 6)
           (screen-width 40)
           (screen-positions (number-sequence 0 (1- (* screen-width screen-height))))
           (pixels (mapcar (lambda (i)
                             (let ((x (elt processed-input i)))
                               (if (<= (1- x) (mod i screen-width) (1+ x))
                                   "#"
                                 ".")))
                           screen-positions
                           )))
      (s-join "\n"
              (seq-partition (s-join "" pixels) screen-width))))

Answer

  (advent/10/draw-screen input)
####.#..#..##..###..#..#..##..###..#..#.
...#.#.#..#..#.#..#.#.#..#..#.#..#.#.#..
..#..##...#....#..#.##...#....#..#.##...
.#...#.#..#.##.###..#.#..#.##.###..#.#..
#....#.#..#..#.#.#..#.#..#..#.#.#..#.#..
####.#..#..###.#..#.#..#..###.#..#.#..#.

Day 11: Monkey in the Middle

Part 1

Assignment

As you finally start making your way upriver, you realize your pack is much lighter than you remember. Just then, one of the items from your pack goes flying overhead. Monkeys are playing Keep Away with your missing things!

To get your stuff back, you need to be able to predict where the monkeys will throw your items. After some careful observation, you realize the monkeys operate based on how worried you are about each item.

You take some notes (your puzzle input) on the items each monkey currently has, how worried you are about those items, and how the monkey makes decisions based on your worry level. For example:

Monkey 0: Starting items: 79, 98 Operation: new = old * 19 Test: divisible by 23 If true: throw to monkey 2 If false: throw to monkey 3

Monkey 1: Starting items: 54, 65, 75, 74 Operation: new = old + 6 Test: divisible by 19 If true: throw to monkey 2 If false: throw to monkey 0

Monkey 2: Starting items: 79, 60, 97 Operation: new = old * old Test: divisible by 13 If true: throw to monkey 1 If false: throw to monkey 3

Monkey 3: Starting items: 74 Operation: new = old + 3 Test: divisible by 17 If true: throw to monkey 0 If false: throw to monkey 1

Each monkey has several attributes:

Starting items lists your worry level for each item the monkey is currently holding in the order they will be inspected. Operation shows how your worry level changes as that monkey inspects an item. (An operation like new = old * 5 means that your worry level after the monkey inspected the item is five times whatever your worry level was before inspection.) Test shows how the monkey uses your worry level to decide where to throw an item next. If true shows what happens with an item if the Test was true. If false shows what happens with an item if the Test was false.

After each monkey inspects an item but before it tests your worry level, your relief that the monkey's inspection didn't damage the item causes your worry level to be divided by three and rounded down to the nearest integer.

The monkeys take turns inspecting and throwing items. On a single monkey's turn, it inspects and throws all of the items it is holding one at a time and in the order listed. Monkey 0 goes first, then monkey 1, and so on until each monkey has had one turn. The process of each monkey taking a single turn is called a round.

When a monkey throws an item to another monkey, the item goes on the end of the recipient monkey's list. A monkey that starts a round with no items could end up inspecting and throwing many items by the time its turn comes around. If a monkey is holding no items at the start of its turn, its turn ends.

In the above example, the first round proceeds as follows:

Monkey 0: Monkey inspects an item with a worry level of 79. Worry level is multiplied by 19 to 1501. Monkey gets bored with item. Worry level is divided by 3 to 500. Current worry level is not divisible by 23. Item with worry level 500 is thrown to monkey 3. Monkey inspects an item with a worry level of 98. Worry level is multiplied by 19 to 1862. Monkey gets bored with item. Worry level is divided by 3 to 620. Current worry level is not divisible by 23. Item with worry level 620 is thrown to monkey 3. Monkey 1: Monkey inspects an item with a worry level of 54. Worry level increases by 6 to 60. Monkey gets bored with item. Worry level is divided by 3 to 20. Current worry level is not divisible by 19. Item with worry level 20 is thrown to monkey 0. Monkey inspects an item with a worry level of 65. Worry level increases by 6 to 71. Monkey gets bored with item. Worry level is divided by 3 to 23. Current worry level is not divisible by 19. Item with worry level 23 is thrown to monkey 0. Monkey inspects an item with a worry level of 75. Worry level increases by 6 to 81. Monkey gets bored with item. Worry level is divided by 3 to 27. Current worry level is not divisible by 19. Item with worry level 27 is thrown to monkey 0. Monkey inspects an item with a worry level of 74. Worry level increases by 6 to 80. Monkey gets bored with item. Worry level is divided by 3 to 26. Current worry level is not divisible by 19. Item with worry level 26 is thrown to monkey 0. Monkey 2: Monkey inspects an item with a worry level of 79. Worry level is multiplied by itself to 6241. Monkey gets bored with item. Worry level is divided by 3 to 2080. Current worry level is divisible by 13. Item with worry level 2080 is thrown to monkey 1. Monkey inspects an item with a worry level of 60. Worry level is multiplied by itself to 3600. Monkey gets bored with item. Worry level is divided by 3 to 1200. Current worry level is not divisible by 13. Item with worry level 1200 is thrown to monkey 3. Monkey inspects an item with a worry level of 97. Worry level is multiplied by itself to 9409. Monkey gets bored with item. Worry level is divided by 3 to 3136. Current worry level is not divisible by 13. Item with worry level 3136 is thrown to monkey 3. Monkey 3: Monkey inspects an item with a worry level of 74. Worry level increases by 3 to 77. Monkey gets bored with item. Worry level is divided by 3 to 25. Current worry level is not divisible by 17. Item with worry level 25 is thrown to monkey 1. Monkey inspects an item with a worry level of 500. Worry level increases by 3 to 503. Monkey gets bored with item. Worry level is divided by 3 to 167. Current worry level is not divisible by 17. Item with worry level 167 is thrown to monkey 1. Monkey inspects an item with a worry level of 620. Worry level increases by 3 to 623. Monkey gets bored with item. Worry level is divided by 3 to 207. Current worry level is not divisible by 17. Item with worry level 207 is thrown to monkey 1. Monkey inspects an item with a worry level of 1200. Worry level increases by 3 to 1203. Monkey gets bored with item. Worry level is divided by 3 to 401. Current worry level is not divisible by 17. Item with worry level 401 is thrown to monkey 1. Monkey inspects an item with a worry level of 3136. Worry level increases by 3 to 3139. Monkey gets bored with item. Worry level is divided by 3 to 1046. Current worry level is not divisible by 17. Item with worry level 1046 is thrown to monkey 1.

After round 1, the monkeys are holding items with these worry levels:

Monkey 0: 20, 23, 27, 26 Monkey 1: 2080, 25, 167, 207, 401, 1046 Monkey 2: Monkey 3:

Monkeys 2 and 3 aren't holding any items at the end of the round; they both inspected items during the round and threw them all before the round ended.

This process continues for a few more rounds:

After round 2, the monkeys are holding items with these worry levels: Monkey 0: 695, 10, 71, 135, 350 Monkey 1: 43, 49, 58, 55, 362 Monkey 2: Monkey 3:

After round 3, the monkeys are holding items with these worry levels: Monkey 0: 16, 18, 21, 20, 122 Monkey 1: 1468, 22, 150, 286, 739 Monkey 2: Monkey 3:

After round 4, the monkeys are holding items with these worry levels: Monkey 0: 491, 9, 52, 97, 248, 34 Monkey 1: 39, 45, 43, 258 Monkey 2: Monkey 3:

After round 5, the monkeys are holding items with these worry levels: Monkey 0: 15, 17, 16, 88, 1037 Monkey 1: 20, 110, 205, 524, 72 Monkey 2: Monkey 3:

After round 6, the monkeys are holding items with these worry levels: Monkey 0: 8, 70, 176, 26, 34 Monkey 1: 481, 32, 36, 186, 2190 Monkey 2: Monkey 3:

After round 7, the monkeys are holding items with these worry levels: Monkey 0: 162, 12, 14, 64, 732, 17 Monkey 1: 148, 372, 55, 72 Monkey 2: Monkey 3:

After round 8, the monkeys are holding items with these worry levels: Monkey 0: 51, 126, 20, 26, 136 Monkey 1: 343, 26, 30, 1546, 36 Monkey 2: Monkey 3:

After round 9, the monkeys are holding items with these worry levels: Monkey 0: 116, 10, 12, 517, 14 Monkey 1: 108, 267, 43, 55, 288 Monkey 2: Monkey 3:

After round 10, the monkeys are holding items with these worry levels: Monkey 0: 91, 16, 20, 98 Monkey 1: 481, 245, 22, 26, 1092, 30 Monkey 2: Monkey 3:

After round 15, the monkeys are holding items with these worry levels: Monkey 0: 83, 44, 8, 184, 9, 20, 26, 102 Monkey 1: 110, 36 Monkey 2: Monkey 3:

After round 20, the monkeys are holding items with these worry levels: Monkey 0: 10, 12, 14, 26, 34 Monkey 1: 245, 93, 53, 199, 115 Monkey 2: Monkey 3:

Chasing all of the monkeys at once is impossible; you're going to have to focus on the two most active monkeys if you want any hope of getting your stuff back. Count the total number of times each monkey inspects items over 20 rounds:

Monkey 0 inspected items 101 times. Monkey 1 inspected items 95 times. Monkey 2 inspected items 7 times. Monkey 3 inspected items 105 times.

In this example, the two most active monkeys inspected items 101 and 105 times. The level of monkey business in this situation can be found by multiplying these together: 10605.

Figure out which monkeys to chase by counting how many items they inspect over 20 rounds. What is the level of monkey business after 20 rounds of stuff-slinging simian shenanigans?

Code

  (defclass monkey nil
    ((number :initarg :number
             :initform 0
             :type (integer 0 *))
     (operation :initarg :operation
                :initform (lambda (o) o)
                :type function)
     (divider :initarg :divider
              :initform 1
              :type integer)
     (next-monkey-true :initarg :next-monkey-true
                       :initform 0
                       :type integer)
     (next-monkey-false :initarg :next-monkey-false
                        :initform 0
                        :type integer)
     (queue :initarg :queue
            :initform nil
            :type list)
     (examination-counter :initarg :examination-counter
                          :initform 0
                          :type integer)
     (worry-drop :initarg :worry-drop
                 :initform 3
                 :type integer)))

  (defun advent/11/parse-expression (expression)
    "Parse the EXPRESSION and return a callable."
    (let ((split-expr (split-string expression " ")))
      (cl-destructuring-bind (op1 operator op2) split-expr
        (read (format "(lambda (old) (%s %s %s))" operator op1 op2)))))

  (defun advent/11/parse-input (input worry-drop)
    "Parse the INPUT, store the amount of WORRY-DROP for each instantiated monkey."
    (mapcar (lambda (s) (monkey
                    :number (string-to-number (nth 1 s))
                    :queue (mapcar #'string-to-number (split-string (nth 2 s) ", "))
                    :operation (advent/11/parse-expression (nth 3 s))
                    :worry-drop worry-drop
                    :divider (string-to-number (nth 4 s))
                    :next-monkey-true (string-to-number (nth 5 s))
                    :next-monkey-false (string-to-number (nth 6 s))
                    ))
            (s-match-strings-all (rx (seq "Monkey" white (group (+ digit)) ":\n"
                                          "  Starting items:" white (group (+ (+ digit) (? ", "))) "\n"
                                          "  Operation: new = " (group (+ alnum) white (any "+" "*" "-" "/") white (+ alnum)) "\n"

                                          "  Test: divisible by " (group (+ digit)) "\n"
                                          "    If true: throw to monkey " (group (+ digit)) "\n"
                                          "    If false: throw to monkey " (group (+ digit))
                                          ))
                                 input)))

  (cl-defmethod queue-item ((m monkey) item)
    "Add ITEM to the monkey's M queue."
    (let ((queue (oref m :queue)))
      (setf (oref m :queue) (append queue (list item)))))

  (cl-defmethod process-queue ((m monkey))
    "Let the monkey M examine the item according to the specification.

  Returns a cons cell specifying which monkey should receive the
  item with the updated worry level."
    (named-let process-item ((result nil))
      (if (oref m :queue)
          (let* ((item (pop (oref m :queue)))
                 (increased-worry-level (funcall (oref m :operation) item))
                 (decreased-worry-level (/ increased-worry-level (oref m :worry-drop)))
                 (next-monkey (if (equal 0 (mod decreased-worry-level (oref m :divider)))
                                  (oref m :next-monkey-true)
                                (oref m :next-monkey-false)))
                 (instruction (cons next-monkey decreased-worry-level)))
            (setf (oref m :examination-counter) (1+ (oref m :examination-counter)))
            (process-item (nconc result (list instruction))))
        result)))

  (defun advent/11/perform-rounds (monkeys rounds)
    "Perform number of ROUNDS on the list of MONKEYS."
    (let* ((dividers (mapcar (lambda (m) (oref m :divider)) monkeys))
           (lcm (-reduce #'* dividers)))
      (dotimes (i rounds)
        (dolist (m monkeys)
          (dolist (dispatched-item (process-queue m))
            (let ((next-monkey (car dispatched-item))
                  (item (cdr dispatched-item)))
              (queue-item (object-assoc next-monkey :number monkeys) (mod item lcm))))))
      monkeys))

  (defun advent/11/count-most-active-monkeys (input rounds &optional worry-drop)
    "Counts the most active monkeys based for the given number of ROUNDS on INPUT.

  Because each the amount of worry to drop depends, it can be given
  as a parameter and is stored along with each instantiated monkey
  from the input."
    (let* ((monkeys (advent/11/parse-input input
                                           (or worry-drop 3)))
           (sorted-monkeys (sort
                            (advent/11/perform-rounds monkeys rounds)
                            (lambda (m1 m2)
                              (>= (oref m1 :examination-counter)
                                  (oref m2 :examination-counter)))))
           (most-active (take 2 sorted-monkeys)))
      (* (oref (car most-active) :examination-counter)
         (oref (cadr most-active) :examination-counter))))

Test

  (defvar advent/11/example-input "Monkey 0:
    Starting items: 79, 98
    Operation: new = old * 19
    Test: divisible by 23
      If true: throw to monkey 2
      If false: throw to monkey 3

  Monkey 1:
    Starting items: 54, 65, 75, 74
    Operation: new = old + 6
    Test: divisible by 19
      If true: throw to monkey 2
      If false: throw to monkey 0

  Monkey 2:
    Starting items: 79, 60, 97
    Operation: new = old * old
    Test: divisible by 13
      If true: throw to monkey 1
      If false: throw to monkey 3

  Monkey 3:
    Starting items: 74
    Operation: new = old + 3
    Test: divisible by 17
      If true: throw to monkey 0
      If false: throw to monkey 1")

  (ert-deftest advent/11/1/example ()
    (should (equal 10605 (advent/11/count-most-active-monkeys advent/11/example-input 20))))

  (ert "advent/11/1/.*")

Answer

  (advent/11/count-most-active-monkeys input 20)
57348

Part 2

Assignment

You're worried you might not ever get your items back. So worried, in fact, that your relief that a monkey's inspection didn't damage an item no longer causes your worry level to be divided by three.

Unfortunately, that relief was all that was keeping your worry levels from reaching ridiculous levels. You'll need to find another way to keep your worry levels manageable.

At this rate, you might be putting up with these monkeys for a very long time - possibly 10000 rounds!

With these new rules, you can still figure out the monkey business after 10000 rounds. Using the same example above:

= After round 1 = Monkey 0 inspected items 2 times. Monkey 1 inspected items 4 times. Monkey 2 inspected items 3 times. Monkey 3 inspected items 6 times.

= After round 20 = Monkey 0 inspected items 99 times. Monkey 1 inspected items 97 times. Monkey 2 inspected items 8 times. Monkey 3 inspected items 103 times.

= After round 1000 = Monkey 0 inspected items 5204 times. Monkey 1 inspected items 4792 times. Monkey 2 inspected items 199 times. Monkey 3 inspected items 5192 times.

= After round 2000 = Monkey 0 inspected items 10419 times. Monkey 1 inspected items 9577 times. Monkey 2 inspected items 392 times. Monkey 3 inspected items 10391 times.

= After round 3000 = Monkey 0 inspected items 15638 times. Monkey 1 inspected items 14358 times. Monkey 2 inspected items 587 times. Monkey 3 inspected items 15593 times.

= After round 4000 = Monkey 0 inspected items 20858 times. Monkey 1 inspected items 19138 times. Monkey 2 inspected items 780 times. Monkey 3 inspected items 20797 times.

= After round 5000 = Monkey 0 inspected items 26075 times. Monkey 1 inspected items 23921 times. Monkey 2 inspected items 974 times. Monkey 3 inspected items 26000 times.

= After round 6000 = Monkey 0 inspected items 31294 times. Monkey 1 inspected items 28702 times. Monkey 2 inspected items 1165 times. Monkey 3 inspected items 31204 times.

= After round 7000 = Monkey 0 inspected items 36508 times. Monkey 1 inspected items 33488 times. Monkey 2 inspected items 1360 times. Monkey 3 inspected items 36400 times.

= After round 8000 = Monkey 0 inspected items 41728 times. Monkey 1 inspected items 38268 times. Monkey 2 inspected items 1553 times. Monkey 3 inspected items 41606 times.

= After round 9000 = Monkey 0 inspected items 46945 times. Monkey 1 inspected items 43051 times. Monkey 2 inspected items 1746 times. Monkey 3 inspected items 46807 times.

= After round 10000 = Monkey 0 inspected items 52166 times. Monkey 1 inspected items 47830 times. Monkey 2 inspected items 1938 times. Monkey 3 inspected items 52013 times.

After 10000 rounds, the two most active monkeys inspected items 52166 and 52013 times. Multiplying these together, the level of monkey business in this situation is now 2713310158.

Worry levels are no longer divided by three after each item is inspected; you'll need to find another way to keep your worry levels manageable. Starting again from the initial state in your puzzle input, what is the level of monkey business after 10000 rounds?

Test

  (ert-deftest advent/11/2/example-1 ()
    (should (equal (* 6 4) (advent/11/count-most-active-monkeys advent/11/example-input 1 1))))

  (ert-deftest advent/11/2/example-2 ()
    (should (equal (* 103 99) (advent/11/count-most-active-monkeys advent/11/example-input 20 1))))

  (ert-deftest advent/11/2/example-long ()
     (should (equal 2713310158 (advent/11/count-most-active-monkeys advent/11/example-input 10000 1))))

  (ert "advent/11/2/.*")

Answer

  (advent/11/count-most-active-monkeys input 10000 1)
14106266886

Day 12: Hill Climbing Algorithm

Part 1

Assignment

You try contacting the Elves using your handheld device, but the river you're following must be too low to get a decent signal.

You ask the device for a heightmap of the surrounding area (your puzzle input). The heightmap shows the local area from above broken into a grid; the elevation of each square of the grid is given by a single lowercase letter, where a is the lowest elevation, b is the next-lowest, and so on up to the highest elevation, z.

Also included on the heightmap are marks for your current position (S) and the location that should get the best signal (E). Your current position (S) has elevation a, and the location that should get the best signal (E) has elevation z.

You'd like to reach E, but to save energy, you should do it in as few steps as possible. During each step, you can move exactly one square up, down, left, or right. To avoid needing to get out your climbing gear, the elevation of the destination square can be at most one higher than the elevation of your current square; that is, if your current elevation is m, you could step to elevation n, but not to elevation o. (This also means that the elevation of the destination square can be much lower than the elevation of your current square.)

For example:

Sabqponm abcryxxl accszExk acctuvwj abdefghi

Here, you start in the top-left corner; your goal is near the middle. You could start by moving down or right, but eventually you'll need to head toward the e at the bottom. From there, you can spiral around to the goal:

v..v<<<< >v.vv<<^ .>vv>E^^ ..v>>>^^ ..>>>>>^

In the above diagram, the symbols indicate whether the path exits each square moving up (^), down (v), left (<), or right (>). The location that should get the best signal is still E, and . marks unvisited squares.

This path reaches the goal in 31 steps, the fewest possible.

What is the fewest steps required to move from your current position to the location that should get the best signal?

Code

  (defun advent/12/input-to-heightmap (input)
    "Parse the given INPUT and returns a height map, the start and end locations.

  The height map is an alist with format (row . col) . height."

    (let ((start) (end))
      (list
       :hmap (-flatten
              (-map-indexed (lambda (row chars)
                              (-map-indexed (lambda (column char)
                                              (cond ((equal char ?S)
                                                     (progn
                                                       (setq start (cons row column))
                                                       (cons (cons row column) ?a)))
                                                    ((equal char ?E)
                                                     (progn
                                                       (setq end (cons row column))
                                                       (cons (cons row column) ?z)))
                                                    (t (cons (cons row column) char))))
                                            (string-to-list chars)))
                            (string-lines input)))
       :start start
       :end end)))

  (defun advent/12/height-at (hmap coordinate)
    (alist-get coordinate hmap nil nil #'equal))

  (defun advent/12/hmap-to-digraph (hmap)
    (let ((edges))
      (mapc (lambda (point)
              (let* ((coordinate (car point))
                     (row (car coordinate))
                     (col (cdr coordinate))
                     (height (cdr point))
                     )

                (dolist (neighbor (list (cons (1- row) col)
                                        (cons (1+ row) col)
                                        (cons row (1- col))
                                        (cons row (1+ col))))

                  (when-let ((neighbor-height (advent/12/height-at hmap neighbor)))
                    (when (<= 0 (- neighbor-height height) 1)
                      (setq edges (append edges (list (cons coordinate neighbor)))))))
                ))
            hmap)
      (list
       :vertices (mapcar #'car hmap)
       :edges edges)))

  (defun advent/12/shortest-path (digraph start end)
    (let* ((vertices (plist-get digraph :vertices))
           (dist (mapcar (lambda (v) (cons v most-positive-fixnum)) vertices))
           (prev (mapcar (\lambda (v) (cons v nil)) vertices)))
      (setf (alist-get start dist nil t #'equal) 0)
      ;; TODO
      dist))

  (defvar advent/12/input "Sabqponm
  abcryxxl
  accszExk
  acctuvwj
  abdefghi")

  (let* ((hmap (advent/12/input-to-heightmap advent/12/input))
         (digraph (advent/12/hmap-to-digraph (plist-get hmap :hmap))))
    (advent/12/shortest-path digraph
                             (plist-get hmap :start)
                             (plist-get hmap :end)))

COMMENT Local variables

Local Variables: org-visibility: t End: