base R
strings
Author

Ella Kaye

Published

December 2, 2022

Setup

The original challenge

My data

Part 1

Toggle the code
library(aochelpers)
input <- aoc_input_vector(2, 2022)
head(input)
[1] "A X" "B Y" "B Y" "C X" "B X" "C Z"

The strategy here is to write a function that calculates the score for each individual round, then use sapply() to apply it to each round in the input, and finally sum the results. The script has a few more details.

Toggle the code
my_score <- function(round) {
    
    draw <- c("A X", "B Y", "C Z")
    win <- c("A Y", "B Z", "C X")
    lose <- c("A Z", "B X", "C Y")
    
    my_shape <- strsplit(round, " ")[[1]][2]
    shape_score <- switch(my_shape, "X" = 1, "Y" = 2, "Z" = 3)
    
    if (round %in% draw) outcome_score <- 3
    else if (round %in% win) outcome_score <- 6
    else outcome_score <- 0
    
    shape_score + outcome_score
}

sapply(input, my_score) |> sum()
[1] 12794

Part 2

Very similar for part 2, expect that the interpretation of the rules is different, so we need to modify the function for caluclating the score.

Toggle the code
my_new_score <- function(round) {
    
    pick_scissors <- c("A X", "B Z", "C Y")
    pick_rock <- c("A Y", "B X", "C Z")
    pick_paper <- c("A Z", "B Y", "C X")
    
    outcome <- strsplit(round, " ")[[1]][2]
    outcome_score <- switch(outcome, "X" = 0, "Y" = 3, "Z" = 6)
    
    if (round %in% pick_rock) shape_score <- 1
    else if (round %in% pick_paper) shape_score <- 2
    else shape_score <- 3
    
    shape_score + outcome_score
}

sapply(input, my_new_score) |> sum()
[1] 14979

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

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