base R
strings
functional programming
Author

Ella Kaye

Published

December 3, 2022

Setup

The original challenge

My data

Part 1

Toggle the code
library(aochelpers)
input <- aoc_input_vector(3, 2022)
head(input)
[1] "hDsDDttbhsmshNNWMNWGbTNqZq"                      
[2] "VQfjnlFvnQFRdZWdVtqMGdWW"                        
[3] "zvvvRnFFfjjlRBlBPzgQgRvvmtrmhHcptLHCDhcHHmLsBmsB"
[4] "FrzFvvdTDcTnmTzdDTTzdvWmjhgVPrhSljSQSPwPjPjPjSVC"
[5] "sMsGbqGsbbRqRbBMBGRMbLpNSSpjhlQljHVClhjgPjjPhlVp"
[6] "sNbGtJbMfssNtvcnWFVmnvDd"                        

Similar to yesterday’s strategy, we define a function to find the priority for the item in both compartments for one rucksack, then apply it to all rucksacks and find the sum. The new-to-me function today is nchar(), to find the number of characters in a string, which we can use with head() and tail() to split the string in half. I also learnt about match(), which returns the position of the first match of the first argument in the second argument.

Toggle the code
priority <- function(rucksack) {
  n <- nchar(rucksack)
  items <- unlist(strsplit(rucksack, ""))
  item <- intersect(head(items, n/2), tail(items, n/2))
  match(item, c(letters, LETTERS))
}

sapply(input, priority) |> sum()
[1] 7821

Part 2

Another opportunity here to use split(), which I learnt about on Day 1, this time to split the input list into groups of three.

Toggle the code
groups <- split(input, rep(1:(length(input)/3), each = 3))

I then define a function to find the priority for the item shared by all three members of one group. strsplit() splits the group into a vector or individual items. intersect() only works on two vectors, so I use Reduce() to apply it to all three.

Toggle the code
priority_shared_item <- function(group) {
  group_items <- strsplit(group, "") 
  common_item <- Reduce(intersect, group_items) 
  match(common_item, c(letters, LETTERS))
}

sapply(groups, priority_shared_item) |> sum()
[1] 2752

Session info

Toggle
─ Session info ───────────────────────────────────────────────────────────────
 setting  value
 version  R version 4.3.1 (2023-06-16)
 os       macOS Sonoma 14.1
 system   aarch64, darwin20
 ui       X11
 language (EN)
 collate  en_US.UTF-8
 ctype    en_US.UTF-8
 tz       Europe/London
 date     2023-11-15
 pandoc   3.1.1 @ /Applications/RStudio.app/Contents/Resources/app/quarto/bin/tools/ (via rmarkdown)
 quarto   1.4.489 @ /usr/local/bin/quarto

─ Packages ───────────────────────────────────────────────────────────────────
 package     * version    date (UTC) lib source
 aochelpers  * 0.0.0.9000 2023-11-15 [1] local
 sessioninfo * 1.2.2      2021-12-06 [1] CRAN (R 4.3.0)

 [1] /Users/ellakaye/Library/R/arm64/4.3/library
 [2] /Library/Frameworks/R.framework/Versions/4.3-arm64/Resources/library

──────────────────────────────────────────────────────────────────────────────