Skip to content

Instantly share code, notes, and snippets.

@xvrdm
Last active December 3, 2021 13:19
Show Gist options
  • Save xvrdm/674fb3d07016e91cd6484d4eb6932e71 to your computer and use it in GitHub Desktop.
Save xvrdm/674fb3d07016e91cd6484d4eb6932e71 to your computer and use it in GitHub Desktop.
Advent of Code 2021 in R - Day 3
library(tidyverse)
binary_flip <- function(x) ifelse(x=="1","0","1")
bits_seq_to_decimal <- function(x) strtoi(paste0(x, collapse = ""), base=2)
# Challenge 1
bits <- readr::read_lines("days/d03/data.txt") %>%
stringr::str_split("")
most_common <- bits %>%
purrr::transpose() %>%
purrr::map(unlist) %>%
purrr::map(~sort(table(.), decreasing=T)) %>%
purrr::map(names) %>%
purrr::map(dplyr::first)
gamma <- bits_seq_to_decimal(most_common)
epsilon <- most_common %>%
purrr::map(binary_flip) %>%
bits_seq_to_decimal
gamma * epsilon
# Challenge 2
most_commons_in_col_n <- function(x, n) {
counts <- purrr::map_chr(x, ~.[n]) %>%
table() %>%
sort(decreasing = TRUE)
ifelse(counts[1] > counts[2], names(counts)[1], "1")
}
o2generator_rating_machine <- function(bits_data, col) {
pred <- most_commons_in_col_n(bits_data, col)
keepers <- purrr::keep(bits_data, ~.[col] == pred)
ifelse(length(keepers) == 1,
keepers[1],
o2generator_rating_machine(keepers, col+1))
}
o2binary <- o2generator_rating_machine(bits, 1)
o2_rating <- bits_seq_to_decimal(o2binary[[1]])
co2scrubber_rating_machine <- function(bits_data, col) {
pred <- binary_flip(most_commons_in_col_n(bits_data, col))
keepers <- purrr::keep(bits_data, ~.[col] == pred)
ifelse(length(keepers) == 1,
keepers,
co2scrubber_rating_machine(keepers, col+1))
}
co2binary <- co2scrubber_rating_machine(bits, 1)
co2_rating <- bits_seq_to_decimal(co2binary[[1]])
o2_rating * co2_rating
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment