Advent of Code 2020

12.R 2.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. library(stringr)
  2. library(dplyr)
  3. input <- readLines("input12.txt") %>% str_match("^(\\w)(\\d+)$") %>% as.data.frame(stringsAsFactors = FALSE)
  4. names(input) <- c("Orig", "Arg", "Param")
  5. input %>% mutate(
  6. Param = as.numeric(Param),
  7. angChange = ifelse(Arg == "R", Param, ifelse(Arg == "L", -Param, 0)),
  8. Angle = cumsum(angChange) %% 360,
  9. MovEast = ifelse(Arg == "E", Param,
  10. ifelse(Arg == "W", -Param,
  11. ifelse(Arg == "F", cos(Angle * pi / 180) * Param, 0))),
  12. MovSouth = ifelse(Arg == "S", Param,
  13. ifelse(Arg == "N", -Param,
  14. ifelse(Arg == "F", sin(Angle * pi / 180) * Param, 0))),
  15. PosEast = cumsum(MovEast),
  16. PosSouth = cumsum(MovSouth)
  17. ) -> shipsLog
  18. mandist <- abs(sum(shipsLog$MovEast)) + abs(sum(shipsLog$MovSouth))
  19. shipsLog %>% select(Orig:Angle) %>%
  20. mutate(
  21. tPMovEast = ifelse(Arg == "E", Param, ifelse(Arg == "W", -Param, 0)),
  22. tPMovSouth = ifelse(Arg == "S", Param, ifelse(Arg == "N", -Param, 0)),
  23. PMovEast = ifelse(Angle == 0, tPMovEast,
  24. ifelse(Angle == 90, tPMovSouth,
  25. ifelse(Angle == 180, -tPMovEast,
  26. -tPMovSouth))),
  27. PMovSouth = ifelse(Angle == 0, tPMovSouth,
  28. ifelse(Angle == 90, -tPMovEast,
  29. ifelse(Angle == 180, -tPMovSouth,
  30. tPMovEast))),
  31. PREastPos = cumsum(PMovEast) + 10,
  32. PRSouthPos = cumsum(PMovSouth) - 1,
  33. PTEastPos = ifelse(Angle == 0, PREastPos,
  34. ifelse(Angle == 90, -PRSouthPos,
  35. ifelse(Angle == 180, -PREastPos,
  36. PRSouthPos))),
  37. PTSouthPos = ifelse(Angle == 0, PRSouthPos,
  38. ifelse(Angle == 90, PREastPos,
  39. ifelse(Angle == 180, -PRSouthPos,
  40. -PREastPos))),
  41. ShipMoveEast = ifelse(Arg == "F", Param * PTEastPos, 0),
  42. ShipMoveSouth = ifelse(Arg == "F", Param * PTSouthPos, 0)
  43. ) -> shipsLog2
  44. mandist2 <- abs(sum(shipsLog2$ShipMoveEast)) + abs(sum(shipsLog2$ShipMoveSouth))