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