Skip to content

Instantly share code, notes, and snippets.

@ursulams
Last active December 21, 2023 03:31
Show Gist options
  • Save ursulams/3ccf5c0a0eefbee5c20dcbf8a9d0f781 to your computer and use it in GitHub Desktop.
Save ursulams/3ccf5c0a0eefbee5c20dcbf8a9d0f781 to your computer and use it in GitHub Desktop.
2023 advent of code day 15
input <- data.frame("label" = t(read.table("input.txt", sep = ",")))
input$row <- seq_along(input[,1])
hasher <- function(x){
current <- 0L
for(i in 1:length(x)){
current <- ((current + utf8ToInt(x[i])) * 17L) %% 256L
}
return(current)
}
input$hash <- sapply(strsplit(input$label, ""), hasher)
sum(input$hash)
#second star
input$length <- sapply(input$label, function(x){as.integer(gsub("[^0-9]", "", x))})
input$label <- sapply(input$label, function(x){gsub("[0-9=-]", "", x)})
input$hash <- sapply(strsplit(input$label, ""), hasher)
# remove lenses up through last "-" in lens group
input$label_id <- with(input, ave(seq_along(label), label, FUN = seq_along))
input <- do.call(rbind, by(input, input$label, function(x)
{transform(x, max_na = ifelse(any(is.na(length)), max(which(is.na(length))), 0))
}))
input <- input[input$label_id > input$max_na, ]
input$hash <- input$hash+1
input <- input[order(input$row), ]
input <- do.call(rbind, lapply(split(input, list(input$label, input$hash)), tail, 1L)) # replace lenses already in boxes
input$slot <- with(input, ave(seq_along(hash), hash, FUN = seq_along))
input$focus <- Reduce(`*`, input[c(3,4,7)])
sum(input$focus)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment