DEV Community

loading...

Advent of Code 2020-06 with R

colinfay profile image Colin Fay Originally published at colinfay.me on ・1 min read

Solving Advent of Code 2020-06 with R.

[Disclaimer] Obviously, this post contains a big spoiler about Advent of Code.

Instructions

Find the complete instructions at:https://adventofcode.com/2020/day/6.

R solution

Part one

library(magrittr)
library(purrr, warn.conflicts = FALSE)
# Read the data
readLines("2020-06-aoc.txt" ) %>% 
  # pasting everything into one big character string
  paste(collapse = "\n") %>% 
  # splitting where there are two \n\n (new lines)
  strsplit("\n\n") %>% 
  .[[1]] %>%
  map_dbl(~ {
    # Removing the new lines of each group
    .x <- gsub("\n", "", .x)
    # Splitting the string
    strsplit(.x, "") %>%
      .[[1]] %>% 
      # Computing the number of unique answer
      unique() %>%
      length()
  }) %>%
  sum()

## [1] 6534
Enter fullscreen mode Exit fullscreen mode

Part two

library(dplyr, warn.conflicts = FALSE)
# Read the data
readLines("2020-06-aoc.txt" ) %>% 
  # pasting everything into one big character string
  paste(collapse = "\n") %>% 
  # splitting where there are two \n\n (new lines)
  strsplit("\n\n") %>% 
  .[[1]] %>%
  map_dbl(~ {
    # Removing the new lines of each group
    x <- strsplit(.x, "\n")[[1]]
    # Getting the group size
    ngroup <- length(x)
    # Splitting the original string
    strsplit(.x, "")[[1]] %>%
      data.frame(
        x = .
      ) %>%
      # Counting the number of occurrences of each letter
      count(x) %>%
      # Keeping only the questions that occur in all
      filter(n == ngroup) %>%
      nrow()
  }) %>%
  sum()

## [1] 3402
Enter fullscreen mode Exit fullscreen mode

Discussion (0)

pic
Editor guide