Advent of Code: Day 19

1 minute read

Parts 1 and 2

input <- readLines("advent-data/2017-12-19-test-data.txt")


puzzle_to_mat <- function(input) {
    input <- strsplit(input, "")

    input_mat <- array(, dim = c(length(input), max(lengths(input))))

    for (i in seq_along(input)) {
        input_mat[i, 1:length(input[[i]])] <- input[[i]]
    }
    input_mat[is.na(input_mat)] <- " "
    input_mat
}

go_down <- function(i, j) {
    c(i + 1, j)
}

go_up <- function(i, j) {
    c(i - 1, j)
}

go_right <- function(i, j) {
    c(i, j + 1)
}

go_left <- function(i, j) {
    c(i, j - 1)
}

navigate_puzzle <- function(puzzle) {

    start <- which(puzzle[1, ] == "|")
    letters_seen <- character(0)
    f <- go_down
    f_nm <- "go_down"
    coords <- c(1, start)
    next_coords <- f(coords[1], coords[2])
    next_char <- puzzle[next_coords[1], next_coords[2]]
    steps <- 0

    while (next_char != " ") {
        while (next_char != "+" && next_char !=  " ") {
            coords <- f(coords[1], coords[2])
            if (any(coords > dim(puzzle)) ||
                any(coords == c(0, 0)))
                break
            next_char <- puzzle[coords[1], coords[2]]
            steps <- steps + 1
            if (grepl("[A-Z]", next_char))
                letters_seen <- c(letters_seen, next_char)
        }
        if (f_nm %in% c("go_down", "go_up")) {
            rght_coords <- go_right(coords[1], coords[2])
            lft_coords <- go_left(coords[1], coords[2])
            if ((!any(rght_coords > dim(puzzle))) &&
                 puzzle[rght_coords[1], rght_coords[2]] != " ") {
                f <- go_right
                f_nm <- "go_right"
                next_char <- puzzle[rght_coords[1], rght_coords[2]]
            } else {
                f <- go_left
                f_nm <- "go_left"
                next_char <- puzzle[lft_coords[1], lft_coords[2]]
            }
        } else {
            up_coords <- go_up(coords[1], coords[2])
            down_coords <- go_down(coords[1], coords[2])
            if ((!any(up_coords > dim(puzzle))) &&
                puzzle[up_coords[1], up_coords[2]] != " ") {
                f <- go_up
                f_nm <- "go_up"
                next_char <- puzzle[up_coords[1], up_coords[2]]
            } else {
                f <- go_down
                f_nm <- "go_down"
                next_char <- puzzle[down_coords[1], down_coords[2]]
            }
        }
        
    }
    list(paste(letters_seen, collapse = ""), steps)
    
}

input <- readLines("advent-data/2017-12-19-test-data.txt")
input <- puzzle_to_mat(input)
navigate_puzzle(input)
## [[1]]
## [1] "ABCDEF"
## 
## [[2]]
## [1] 38
input_puzzle <- readLines("advent-data/2017-12-19-data.txt")
input_puzzle <- puzzle_to_mat(input_puzzle)

navigate_puzzle(input_puzzle)
## [[1]]
## [1] "UICRNSDOK"
## 
## [[2]]
## [1] 16064

Leave a Comment