Advent of Code 2020

4.R 1.1KB

12345678910111213141516171819202122232425
  1. library(dplyr)
  2. library(stringr)
  3. library(tidyr)
  4. input <- readLines("input4.txt") %>% paste(collapse = "\n") %>% str_split("\n\n") %>% unlist() %>% str_replace_all("\n", " ")
  5. flds <- str_match(input, "([a-z]+):")[,2] %>% unique()
  6. df <- data.frame(Orig = input)
  7. for (f in flds) {
  8. df[[f]] <- str_match(input, paste0(f, ":([a-zA-Z0-9#]+)"))[,2]
  9. }
  10. df.valid <- df %>% drop_na(-cid)
  11. str(df)
  12. str(df.valid)
  13. nrow(df.valid)
  14. ecs <- c("amb", "blu", "brn", "gry", "grn", "hzl", "oth")
  15. df.valid %>% mutate(
  16. byr = ifelse(between(as.numeric(str_match(byr, "^([0-9]+)$")[,2]), 1920, 2002), byr, NA),
  17. iyr = ifelse(between(as.numeric(str_match(iyr, "^([0-9]+)$")[,2]), 2010, 2020), iyr, NA),
  18. eyr = ifelse(between(as.numeric(str_match(eyr, "^([0-9]+)$")[,2]), 2020, 2030), eyr, NA),
  19. hgt = ifelse(between(as.numeric(str_match(hgt, "^([0-9]+)cm$")[,2]), 150, 193) | between(as.numeric(str_match(hgt, "^([0-9]+)in$")[,2]), 59, 76), hgt, NA),
  20. hcl = str_extract(hcl, "^[#]{1}[0-9a-f]{6}$"),
  21. ecl = ifelse(ecl %in% ecs, ecl, NA),
  22. pid = str_extract(pid, "^[0-9]{9}$")
  23. ) %>% drop_na(-cid) -> dv2
  24. nrow(dv2)