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

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay