-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathREADME.qmd
398 lines (298 loc) · 10 KB
/
README.qmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
---
title: Advent of Code 2022
author: Alexander Enge
date: 2022-12-01
format:
gfm:
toc: true
toc-depth: 2
---
Hi! :wave:
This repository contains my solutions for the [2022 edition](https://adventofcode.com/2022) of [Advent of Code](https://adventofcode.com).
From the Advent of Code website:
> **Advent of Code** is an [Advent calendar](https://en.wikipedia.org/wiki/Advent_calendar) of small programming puzzles for a variety of skill sets and skill levels that can be solved in any programming language you like.
> People use them as interview prep, company training, university coursework, practice problems, a speed contest, or to challenge each other.
I'll be using a mix of [Python](https://www.python.org), [Base R](https://www.r-project.org), and [tidyverse-style R](https://www.tidyverse.org).
## Day 1: Calorie Counting :pizza:
### Part one: Python
```{python}
max_elf = 0
this_elf = 0
with open('data/day1.txt') as f:
for line in f:
if this_elf > max_elf:
max_elf = this_elf
if line == '\n':
this_elf = 0
else:
this_elf += int(line.strip())
print(max_elf)
```
### Part one: Base R
```{r}
lines <- readLines("data/day1.txt", warn = FALSE)
elf_indices <- cumsum(lines == "")
split(lines, elf_indices) |>
lapply(as.numeric) |>
lapply(sum, na.rm = TRUE) |>
unlist() |>
max()
```
### Part two: Python
```{python}
max_elves = [0, 0, 0]
this_elf = 0
with open('data/day1.txt') as f:
for line in f:
max_elves.sort()
if this_elf > max_elves[0]:
max_elves[0] = this_elf
if line == '\n':
this_elf = 0
else:
this_elf += int(line.strip())
print(sum(max_elves))
```
### Part two: Base R
```{r}
lines <- readLines("data/day1.txt", warn = FALSE)
elf_indices <- cumsum(lines == "")
split(lines, elf_indices) |>
lapply(as.numeric) |>
lapply(sum, na.rm = TRUE) |>
unlist() |>
sort() |>
tail(3) |>
sum()
```
## Day 2: Rock Paper Scissors :scissors:
### Part one: Tidyverse R
```{r, message = FALSE}
library(tidyverse)
read_table("data/day2.txt", col_names = c("other", "me")) %>%
unite(col = "round", other, me, remove = FALSE) %>%
mutate(
game_score = case_when(
round %in% c("A_Y", "B_Z", "C_X") ~ 6,
round %in% c("A_X", "B_Y", "C_Z") ~ 3,
round %in% c("A_Z", "B_X", "C_Y") ~ 0
),
play_score = recode(me, "X" = 1, "Y" = 2, "Z" = 3),
score = game_score + play_score
) %>%
pull(score) %>%
sum()
```
### Part two: Tidyverse R
```{r, message = FALSE}
read_table("data/day2.txt", col_names = c("other", "outcome")) %>%
unite(col = "round", other, outcome, remove = FALSE) %>%
mutate(
me = case_when(
round %in% c("A_X", "B_Z", "C_Y") ~ "Z",
round %in% c("A_Y", "B_X", "C_Z") ~ "X",
round %in% c("A_Z", "B_Y", "C_X") ~ "Y"
),
game_score = recode(outcome, "X" = 0, "Y" = 3, "Z" = 6),
play_score = recode(me, "X" = 1, "Y" = 2, "Z" = 3),
score = game_score + play_score
) %>%
pull(score) %>%
sum()
```
## Day 3: Rucksack Reorganization :school_satchel:
### Part one: Python
```{python}
from string import ascii_lowercase, ascii_uppercase
with open('data/day3.txt') as f:
lines = [line.strip() for line in f.readlines()]
halves = [(line[:len(line) // 2], line[len(line) // 2:]) for line in lines]
items = [set(half_1).intersection(half_2).pop() for half_1, half_2 in halves]
letters = ascii_lowercase + ascii_uppercase
priorities = [letters.index(item) + 1 for item in items]
print(sum(priorities))
```
### Part two: Python
```{python}
group_size = 3
groups = [lines[ix:ix + group_size] for ix in range(0, len(lines), group_size)]
badges = [set.intersection(*map(set, group)).pop() for group in groups]
priorities = [letters.index(badge) + 1 for badge in badges]
print(sum(priorities))
```
## Day 4: Camp Cleanup :broom:
### Part one: Python
```{python}
def is_contained(min_1, max_1, min_2, max_2):
return (min_1 >= min_2 and max_1 <= max_2 or
min_2 >= min_1 and max_2 <= max_1)
contained = 0
with open('data/day4.txt') as f:
for line in f:
elf_1, elf_2 = line.strip().split(',')
min_1, max_1 = [int(section) for section in elf_1.split('-')]
min_2, max_2 = [int(section) for section in elf_2.split('-')]
contained += is_contained(min_1, max_1, min_2, max_2)
print(contained)
```
### Part one: Tidyverse R
```{r, message = FALSE}
read_csv("data/day4.txt", col_names = c("elf_1", "elf_2")) %>%
transmute(across(.fns = str_split, pattern = "-")) %>%
unnest_wider(c(elf_1, elf_2), names_sep = "_", transform = as.integer) %>%
mutate(
contained_1 = elf_1_1 >= elf_2_1 & elf_1_2 <= elf_2_2,
contained_2 = elf_2_1 >= elf_1_1 & elf_2_2 <= elf_1_2,
contained = contained_1 | contained_2
) %>%
pull(contained) %>%
sum()
```
### Part two: Python
```{python}
def is_overlap(min_1, max_1, min_2, max_2):
return (max_1 >= min_2 and max_2 >= min_1)
overlaps = 0
with open('data/day4.txt') as f:
for line in f:
elf_1, elf_2 = line.strip().split(',')
min_1, max_1 = [int(section) for section in elf_1.split('-')]
min_2, max_2 = [int(section) for section in elf_2.split('-')]
overlaps += is_overlap(min_1, max_1, min_2, max_2)
print(overlaps)
```
### Part two: Tidyverse R
```{r, message = FALSE}
read_csv("data/day4.txt", col_names = c("elf_1", "elf_2")) %>%
transmute(across(.fns = str_split, pattern = "-")) %>%
unnest_wider(c(elf_1, elf_2), names_sep = "_", transform = as.integer) %>%
mutate(overlap = elf_1_2 >= elf_2_1 & elf_2_2 >= elf_1_1) %>%
pull(overlap) %>%
sum()
```
## Day 5: Supply Stacks :building_construction:
### Part one: Base R
```{r}
transpose_list <- function(l) as.list(as.data.frame(t(as.data.frame(l))))
drop_empty <- function(x) x[x != " "]
input <- read.csv("data/day5.txt", header = FALSE)
input_1 <- subset(input, grepl("\\[", V1))$V1
stack_ixs <- seq(2, max(nchar(input_1)), by = 4)
stacks <- lapply(input_1, substring, first = stack_ixs, last = stack_ixs) |>
rev() |>
transpose_list() |>
lapply(drop_empty)
input_2 <- subset(input, grepl("move", V1))$V1
moves <- strsplit(input_2, split = " ")
for (move in moves) {
from = as.integer(move[4])
to = as.integer(move[6])
n = as.integer(move[2])
stacks[[to]] <- c(stacks[[to]], rev(tail(stacks[[from]], n)))
stacks[[from]] <- head(stacks[[from]], -n)
}
lapply(stacks, tail, n = 1) |>
paste(collapse = "")
```
### Part two: Base R
```{r}
stacks <- lapply(input_1, substring, first = stack_ixs, last = stack_ixs) |>
rev() |>
transpose_list() |>
lapply(drop_empty) # Same as before
for (move in moves) {
from = as.integer(move[4])
to = as.integer(move[6])
n = as.integer(move[2])
stacks[[to]] <- c(stacks[[to]], tail(stacks[[from]], n)) # Don't reverse
stacks[[from]] <- head(stacks[[from]], -n)
}
lapply(stacks, tail, n = 1) |>
paste(collapse = "")
```
## Day 6: Tuning Trouble :radio:
### Part one: Python
```{python}
def find_marker(input, n_letters):
for ix in range(len(input)):
letters = input[ix:ix + n_letters]
if len(letters) == len(set(letters)):
return ix + n_letters
with open('data/day6.txt') as f:
input = f.readline()
find_marker(input, n_letters=4)
```
### Part two: Python
```{python}
find_marker(input, n_letters=14)
```
## Day 7: No Space Left On Device :file_folder:
### Part one: Base R
```{r}
input <- readLines("data/day7.txt", warn = FALSE)
dirs = list(`/` = list(".dir_size" = 0))
for (cmd in input) {
if (cmd == "$ cd /") path <- '/'
else if (cmd == "$ cd ..") path <- head(path, -1)
else if (startsWith(cmd, "$ cd")) {
dir_name <- tail(strsplit(cmd, " ")[[1]], 1)
path <- c(path, dir_name)
}
else if (cmd == "$ ls") dirs[[path]] <- list(".dir_size" = 0)
else if (!startsWith(cmd, "dir")) { # Only consider files, not directories
file_size <- strsplit(cmd, " ")[[1]] |> head(1) |> as.numeric()
for (ix in seq_along(path)) { # Add file size to all parent directories
dir_size_path <- c(head(path, ix), ".dir_size")
dirs[[dir_size_path]] <- dirs[[dir_size_path]] + file_size
}
}
else next
}
str(dirs, list.len = 3) # Sanity check
dir_sizes <- unlist(dirs)
sum(dir_sizes[dir_sizes < 1e5])
```
### Part two: Base R
```{r}
space_left <- 7e7 - dirs[[c("/", ".dir_size")]]
space_needed <- 3e7 - space_left
min(dir_sizes[dir_sizes > space_needed])
```
## Day 8: Treetop Tree House :deciduous_tree:
### Part one: Python
```{python}
import numpy as np
def is_visible(arr_1d):
"""Tests for each element in arr if it's visible from the front or back."""
return [all(arr_1d[:ix] < elem) or all(arr_1d[ix + 1:] < elem)
for ix, elem in enumerate(arr_1d)]
input = np.genfromtxt('data/day8.txt', delimiter=1)
vis = [np.apply_along_axis(is_visible, ax, input) for ax in range(input.ndim)]
np.any(vis, axis=0).sum()
```
### Part two: Python
```{python}
def score_elem(arr, elem):
"""Computes the score (other visible trees) in one direction."""
if arr.size == 0:
score = 0 # Edge tree
elif all(elem > arr):
score = len(arr) # Largest tree, sees all other trees in the row
else:
score = np.where(arr >= elem)[0][0] + 1 # Sees until next equal tree
return score
input = np.genfromtxt('data/day8.txt', dtype=int, delimiter=1)
scores = np.zeros((4,) + input.shape, dtype=int)
for row_ix, row in enumerate(input):
for col_ix, elem in enumerate(row):
left = np.flip(row[:col_ix])
right = row[col_ix + 1:]
up = np.flip(input[:row_ix, col_ix])
down = input[row_ix + 1:, col_ix]
for dir_ix, arr in enumerate([left, right, up, down]):
scores[dir_ix, row_ix, col_ix] = score_elem(arr, elem)
scores = np.prod(scores, axis=0)
print(scores.max())
```
That's how far I've got for the 2022 edition of Advent of Code. :facepalm:
Wish me better luck next time!