Day 2: Dive!

Reference

Part One

library(tidyverse)

commands <- read_delim(file      = "inputs/2021/02.txt",
                       col_names = c("direction", "length"))

commands <- commands |> 
    mutate(x = if_else(direction == "forward", 1, 0),
           y = case_match(direction,
                          "down"    ~ 1,
                          "forward" ~ 0,
                          "up"      ~ -1)) |> 
    select(-direction) |> 
    mutate(across(everything(), as.integer)) |>
    mutate(x = x * length,
           y = y * length)

commands |>
    summarise(x = sum(x),
              y = sum(y)) |>
    mutate(product = x * y) |>
    pull(product) |>
    cat()
## 1762050

Part Two

commands <- read_delim(file      = "inputs/2021/02.txt",
                       col_names = c("direction", "length")) |> 
    mutate(aim = NA_real_, x = NA_real_, y = NA_real_) |> 
    add_row(direction = NA, length = NA, aim = 0, x = 0, y = 0, .before = 1)

for (i in 2:nrow(commands)){
    if (commands[i, "direction"] == "down") {
        commands[i, "aim"] = commands[i-1, "aim"] + commands[i, "length"]
        commands[i, "x"]   = commands[i-1, "x"]
        commands[i, "y"]   = commands[i-1, "y"]
    }
    
    else if (commands[i, "direction"] == "up") {
        commands[i, "aim"] = commands[i-1, "aim"] - commands[i, "length"]
        commands[i, "x"]   = commands[i-1, "x"]
        commands[i, "y"]   = commands[i-1, "y"]
    }
    
    else if (commands[i, "direction"] == "forward") {
        commands[i, "aim"] = commands[i-1, "aim"]
        commands[i, "x"]   = commands[i-1, "x"] + commands[i, "length"]
        commands[i, "y"]   = commands[i-1, "y"] + commands[i, "aim"] * commands[i, "length"]
    }
}

commands |>
    slice(nrow(commands)) |> 
    mutate(product = x * y) |> 
    pull(product) |> 
    cat()
## 1855892637