Advent of Code 2020

7.R 1.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. library(stringr)
  2. library(dplyr)
  3. input <- readLines("input7.txt")
  4. # pc <- str_match(input, "^(\\w+\\W\\w+\\W\\w+) contain (.*)\\.$")
  5. pc <- str_match(input, "^(.*) bags contain (.*)\\.$")
  6. parents <- pc[,2]
  7. childs <- pc[,3]
  8. head(pc)
  9. head(parents)
  10. head(childs)
  11. nodes <- lapply(childs, function(n) {
  12. nodv <- sapply(str_split(n, ", ")[[1]], function(nv) {
  13. v <- as.numeric(str_match(nv, "(^\\d+) .* bags?$")[,2])
  14. return(v)
  15. })
  16. # bcols <-
  17. nds <- str_match(names(nodv), "^\\d+ (.*) bags?$")
  18. names(nodv) <- nds[,2]
  19. nodv
  20. })
  21. names(nodes) <- parents
  22. head(nodes)
  23. # Part 1
  24. bags <- c()
  25. nbags <- c("shiny gold")
  26. cont <- TRUE
  27. while (cont) { #this would probably be better recursively but urgh
  28. ebags <- sapply(nodes, function(n) {
  29. TRUE %in% (nbags %in% names(n))
  30. })
  31. bags <- unique(c(bags, nbags))
  32. nbags <- names(nodes)[ebags]
  33. cont <- min(nbags %in% bags) == 0
  34. }
  35. # Part 2
  36. numbags <- function(bag) {
  37. nbags <- nodes[[bag]]
  38. sbags <- names(nbags)
  39. v <- 0
  40. if (length(nbags) > 0) {
  41. v <- sum(sapply(sbags, numbags) * nbags)
  42. }
  43. ifelse(is.na(v), 1, v + 1)
  44. }
  45. bag <- "shiny gold"
  46. numbags(bag) - 1