Advent of Code 2020

16.R 2.0KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. library(stringr)
  2. library(dplyr)
  3. input <- readLines("input16.txt")
  4. input <- unlist(str_split(paste0(input, collapse = "\n"), "\n\n"))
  5. params <- str_match(unlist(str_split(input[1], "\n")), "^([a-z ]+): (\\d+)-(\\d+) or (\\d+)-(\\d+)$")
  6. params <- as.data.frame(params, stringsAsFactors = FALSE)
  7. names(params) <- c("Orig", "Param", "Min1", "Max1", "Min2", "Max2")
  8. params <- mutate(params,
  9. Min1 = as.numeric(Min1),
  10. Max1 = as.numeric(Max1),
  11. Min2 = as.numeric(Min2),
  12. Max2 = as.numeric(Max2)
  13. )
  14. bound1 <- params %>% select(Min1:Max1) %>% as.matrix()
  15. bound2 <- params %>% select(Min2:Max2) %>% as.matrix()
  16. bounds <- rbind(bound1, bound2)
  17. boundsb <- cbind(bound1, bound2)
  18. myticket <- as.numeric(unlist(str_split(str_split(input[2], "\n")[[1]][2], ",")))
  19. alltickets <- do.call(rbind, str_split(unlist(str_split(input[3],"\n"))[-1], "," ))
  20. alltickets <- matrix(as.numeric(alltickets), nrow = nrow(alltickets))
  21. posvalid <- apply(alltickets, c(1, 2), function(x) {
  22. any(apply(bounds, 1, function(b) {
  23. (x >= b[1]) && (x <= b[2])
  24. }))
  25. })
  26. sum(alltickets[!posvalid])
  27. tvalid <- apply(posvalid, 1, min) != 0
  28. vtickets <- alltickets[tvalid,]
  29. possmatrix <- apply(boundsb, 1, function(b) {
  30. vmatrix <- apply(vtickets, c(1, 2), function(x) {
  31. ((x >= b[1]) && (x <= b[2])) || ((x >= b[3]) && (x <= b[4]))
  32. })
  33. apply(vmatrix, 2, all)
  34. })
  35. potnums <- apply(possmatrix, 1, sum)
  36. potorder <- order(potnums)
  37. colindex <- numeric(0)
  38. matordered <- possmatrix[potorder,]
  39. apply(matordered, 1, function(r) {
  40. cb <- which(r)
  41. cb <- cb[!(cb %in% colindex)]
  42. colindex <<- c(colindex, cb)
  43. cb
  44. })
  45. depcols <- colindex[grepl("^departure ", params$Param[potorder])]
  46. print(prod(myticket[depcols]), digits = 15)
  47. params$Param[potorder]
  48. 2529157555213
  49. cbind(params$Param[potorder], colindex)