Advent of Code 2020 Day 1

Author

Nathan Moore

— Day 1: Report Repair —

The elves give you an expense report and need you to fix things up.

Of course, your expense report is much larger. Find the two entries that sum to 2020; what do you get if you multiply them together?

library(tidyverse)
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.1.4     ✔ readr     2.1.6
✔ forcats   1.0.1     ✔ stringr   1.6.0
✔ ggplot2   4.0.1     ✔ tibble    3.3.0
✔ lubridate 1.9.4     ✔ tidyr     1.3.1
✔ purrr     1.2.0     
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag()    masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
input_file <- here::here("2020", "data-2020-01.txt")
my_input <- readLines(input_file) %>% as.numeric()
Warning in readLines(input_file): incomplete final line found on
'C:/Users/NathanMoore/code/advent-of-code/2020/data-2020-01.txt'

Let’s have a look at the data

# for plotting
df = as.data.frame(my_input)

# have a look
ggplot(df) + 
  geom_histogram(aes(my_input))
`stat_bin()` using `bins = 30`. Pick better value `binwidth`.

# there is probably some value in sorting the list
# lower values are likely to be included rather than two around 1000
sorted_list = sort(my_input)

# double loop
for (x in seq_along(sorted_list)) {
  for (y in seq_along(sorted_list)) {
    if (sorted_list[[x]] + sorted_list[[y]] == 2020) {
      print(sorted_list[[x]] * sorted_list[[y]])
    }
  }
}
[1] 1005459
[1] 1005459

— Part Two —

Actually, find three numbers that sum to 2020.

In your expense report, what is the product of the three entries that sum to 2020?

# triple loop
for (x in seq_along(sorted_list)) {
  for (y in seq_along(sorted_list)) {
    for (z in seq_along(sorted_list)) {
      if (sorted_list[[x]] + sorted_list[[y]] + sorted_list[[z]] == 2020) {
        print(sorted_list[[x]] * sorted_list[[y]] * sorted_list[[z]])
      }
    }
  }
}
[1] 92643264
[1] 92643264
[1] 92643264
[1] 92643264
[1] 92643264
[1] 92643264