DEV Community

Colin Fay
Colin Fay

Posted on • Originally published at colinfay.me on

Advent of Code 2020-06 with R

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

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up