Day 2: Password Philosophy

Reference

Part One

library(tidyverse)

input <- read_lines(file = "inputs/2020/02.txt")

passwords <- tibble(original = input) |> 
    
    separate_wider_delim(cols = original,
                         names = c("range", "letter", "password"),
                         delim = " ") |>
    
    mutate(letter = str_replace(string = letter,
                                pattern = ":",
                                replacement = "")) |>
    
    separate_wider_delim(cols = range, names = c("min", "max"), delim = "-") |> 
    
    mutate(across(c(min, max), as.integer))

validation_1 <- passwords |> 
    mutate(matches = str_count(password, pattern = letter),
           valid   = between(matches, min, max))

validation_1
## # A tibble: 1,000 × 6
##      min   max letter password             matches valid
##    <int> <int> <chr>  <chr>                  <int> <lgl>
##  1    15    16 l      klfbblslvjclmlnqklvg       6 FALSE
##  2     6    13 h      pghjchdxhnjhjd             4 FALSE
##  3     4    13 n      nnznntzznqnzbtzj           6 TRUE 
##  4    10    16 r      nrrrrkrjtxwrrrwx           8 FALSE
##  5     1     6 t      rttftttttttttmdttttt      16 FALSE
##  6     4    12 l      zhllfxlmvqtnhx             3 FALSE
##  7     6     8 d      wxpwgdbjtffddkb            3 FALSE
##  8     7     9 q      rqcqxjqhsm                 3 FALSE
##  9     6     8 x      xxxfxdxxx                  7 TRUE 
## 10     5     9 d      dwnwnbsddfmc               3 FALSE
## # ℹ 990 more rows

validation_1 |> 
    count(valid) |> 
    filter(valid == TRUE) |> 
    pull(n) |> 
    cat()
## 424

Part Two

validation_2 <- passwords |> 
    mutate(first   = str_sub(password, start = min, end = min),
           second  = str_sub(password, start = max, end = max),
           matches = (first == letter) + (second == letter))

validation_2
## # A tibble: 1,000 × 7
##      min   max letter password             first second matches
##    <int> <int> <chr>  <chr>                <chr> <chr>    <int>
##  1    15    16 l      klfbblslvjclmlnqklvg n     q            0
##  2     6    13 h      pghjchdxhnjhjd       h     j            1
##  3     4    13 n      nnznntzznqnzbtzj     n     b            1
##  4    10    16 r      nrrrrkrjtxwrrrwx     x     x            0
##  5     1     6 t      rttftttttttttmdttttt r     t            1
##  6     4    12 l      zhllfxlmvqtnhx       l     n            1
##  7     6     8 d      wxpwgdbjtffddkb      d     j            1
##  8     7     9 q      rqcqxjqhsm           q     s            1
##  9     6     8 x      xxxfxdxxx            d     x            1
## 10     5     9 d      dwnwnbsddfmc         n     d            1
## # ℹ 990 more rows

validation_2 |> 
    filter(matches == 1) |> 
    nrow() |> 
    cat()
## 747