Categories
#rstats

Advent of Code 2017 in #rstats: Day 1

Today’s puzzle is a good example of thinking “R-ishly”.   In R, I find it easier to compare vectors than to compare strings, and easier to work with vectorized functions than to loop.  So my code starts by splitting the input into a vector.

Part 1:

Split the input into a vector, add the first value to the end, and use dplyr’s lead() function to compare each value to the following value:

library(stringr)
library(dplyr)

target <- "112345567891" # should yield 1 + 5 + 1 = 7
target <- str_split(target, "") %>% unlist %>% as.numeric() # split input string into a vector:
target <- c(target, target[1]) # add the first value to the end, to account for wrap-around
sum(target[target == lead(target)], na.rm = TRUE) # sum every number that matches the number following it

Part 2:

This challenge is simpler, in my opinion.  You can halve the vector, then compare the first half to the second half, summing the matches (don’t forget to double that result).

target <- "123425" # should match both 2s for a total of 4
target <- str_split(target, "") %>% unlist %>% as.numeric()
first_half <- target[1:(length(target)/2)]
second_half <- target[-c(1:(length(target)/2))]
sum(first_half[first_half == second_half], na.rm = TRUE) * 2

Leave a Reply

Your email address will not be published. Required fields are marked *