|
| 1 | +#####SETUP##### |
| 2 | +# libraries |
| 3 | +library(tidyverse) |
| 4 | + |
| 5 | +# input file name (change for test data to actual input data) |
| 6 | +input_file <- "day5.in" |
| 7 | + |
| 8 | +# utility functions |
| 9 | +first_index_of <- function(val, vec) { |
| 10 | + search_val <- which(val == vec) |
| 11 | + |
| 12 | + if (length(search_val) > 0) return(search_val[1]) |
| 13 | + else return(NA) |
| 14 | +} |
| 15 | + |
| 16 | +get_indices <- function(vec_find, vec_in) { |
| 17 | + vapply(X = vec_find, |
| 18 | + FUN = function(val) first_index_of(val, vec_in), |
| 19 | + FUN.VALUE = integer(1), |
| 20 | + USE.NAMES = FALSE) |
| 21 | +} |
| 22 | + |
| 23 | +#####PART 1##### |
| 24 | +# input |
| 25 | +con <- file(input_file, "r") |
| 26 | +temp <- readLines(con) |
| 27 | +blank_index <- which(temp == "") |
| 28 | +n_rows <- length(temp) |
| 29 | +close(con) |
| 30 | + |
| 31 | +input_order <- read.delim(input_file, header = FALSE, nrows = blank_index - 1, sep = "|") %>% |
| 32 | + as_tibble %>% |
| 33 | + rename(before = V1, after = V2) |
| 34 | + |
| 35 | +# process |
| 36 | +counter <- 0 |
| 37 | +for (curr_row in seq(from = blank_index + 1, to = n_rows)) { |
| 38 | + # get input row |
| 39 | + curr_input <- temp[curr_row] %>% |
| 40 | + strsplit(split = ",", fixed = TRUE) %>% |
| 41 | + unlist %>% |
| 42 | + as.integer |
| 43 | + curr_len <- length(curr_input) |
| 44 | + |
| 45 | + # calculate indices |
| 46 | + curr_df <- input_order %>% |
| 47 | + mutate(Before_Ind = get_indices(before, curr_input), |
| 48 | + After_Ind = get_indices(after, curr_input)) %>% |
| 49 | + filter(!is.na(Before_Ind)) %>% |
| 50 | + filter(!is.na(After_Ind)) %>% |
| 51 | + filter(Before_Ind > After_Ind) |
| 52 | + |
| 53 | + # check if any violations |
| 54 | + if (nrow(curr_df) > 0) next |
| 55 | + |
| 56 | + # if no violations, add to counter |
| 57 | + counter <- counter + curr_input[ceiling(curr_len / 2)] |
| 58 | +} |
| 59 | + |
| 60 | +# output |
| 61 | +print(counter) |
0 commit comments