Aloha, welcome to the third day of Advent of Code 2021. Again, I am going to solve this puzzle using Base R. Please see https://adventofcode.com/2021/day/3 for the problem description.
Part 1:
bin_data <- read.csv(file = "day_three", col.names = "bin", header = FALSE, colClasses = "character")
head(bin_data)
## bin
## 1 110011110101
## 2 110011100010
## 3 010100011010
## 4 011001100000
## 5 010011011101
## 6 011110111000
bin_m <- matrix(data = as.integer(unlist(strsplit(bin_data[["bin"]], split = ""))), ncol = 12, byrow = TRUE)
head(bin_m)
## [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
## [1,] 1 1 0 0 1 1 1 1 0 1 0 1
## [2,] 1 1 0 0 1 1 1 0 0 0 1 0
## [3,] 0 1 0 1 0 0 0 1 1 0 1 0
## [4,] 0 1 1 0 0 1 1 0 0 0 0 0
## [5,] 0 1 0 0 1 1 0 1 1 1 0 1
## [6,] 0 1 1 1 1 0 1 1 1 0 0 0
gamma <- as.integer(colSums(bin_m) > nrow(bin_data)/2)
epsilon <- as.integer(colSums(bin_m) < nrow(bin_data)/2)
gamma <- strtoi(paste(gamma, collapse = ""), base = 2)
epsilon <- strtoi(paste(epsilon, collapse = ""), base = 2)
(answer <- gamma * epsilon)
## [1] 2967914
Part 2:
Solved by a while loop, indexing the columns of bin_m. Guess what, loops are still cool in R ;-)
i <- 1L
while(i <= ncol(bin_m)) {
filter_m <- ifelse(sum(bin_m[, i]) >= nrow(bin_m)/2, 1, 0)
bin_m <- bin_m[bin_m[, i] == filter_m,]
i <- i + 1L
if(is.null(nrow(bin_m))) break
}
ox <- strtoi(paste(bin_m, collapse = ""), base = 2)
Computing co2 is basically the same. Sorry for repitition.
bin_m <- matrix(data = as.integer(unlist(strsplit(bin_data[["bin"]], split = ""))), ncol = 12, byrow = TRUE)
i <- 1L
while(i <= ncol(bin_m)) {
filter_m <- ifelse(sum(bin_m[, i]) >= nrow(bin_m)/2, 0, 1)
bin_m <- bin_m[bin_m[, i] == filter_m,]
i <- i + 1L
if(is.null(nrow(bin_m))) break
}
co_2 <- strtoi(paste(bin_m, collapse = ""), base = 2)
(answer <- co_2 * ox)
## [1] 7041258
See you!