Skip to content

Instantly share code, notes, and snippets.

@ursulams
Created December 11, 2023 00:55
Show Gist options
  • Save ursulams/5e96d7c5433d99a95cabfe11eda3cdc5 to your computer and use it in GitHub Desktop.
Save ursulams/5e96d7c5433d99a95cabfe11eda3cdc5 to your computer and use it in GitHub Desktop.
2023 advent of code day 7
# first star
hands <- data.frame(read.table("hands.txt", header = FALSE, sep = " ", col.names = c("cards", "bid")))
hands$hand <- lapply(strsplit(hands$cards, ""), function(x){
type.convert(gsub("A", 14,
gsub("K", 13,
gsub("Q", 12,
gsub("J", 11,
gsub("T", 10, x))))), as.is = TRUE)
})
hands$hand_rank <- sapply(hands$hand, function(x){
ifelse(length(which(table(x)==5)), 7,
ifelse(length(which(table(x)==4)), 6,
ifelse((max(table(x))==3 & min(table(x))==2), 5,
ifelse((max(table(x))==3 & min(table(x))<2), 4,
ifelse(sum(table(x)==2)==2, 3,
ifelse(sum(table(x)==2)==1, 2, 1))))))
})
hands <- cbind(hands[, c("bid", "hand_rank")], do.call(rbind, hands$hand))
hands <- hands[order(hands[,2], hands[,3], hands[,4], hands[,5], hands[,6], hands[,7], decreasing = FALSE), ]
hands$final_rank <- seq_along(hands[,1])
hands$winnings <- hands$bid*hands$final_rank
sum(hands$winnings)
# second star
hands <- data.frame(read.table("hands.txt", header = FALSE, sep = " ", col.names = c("cards", "bid")))
hands$with_joker <- sapply(hands$cards, function(x){
ranks <- c("A", "K", "Q", "T", "9", "8", "7", "6", "5", "4", "3", "2", "J")
tab <- table(unlist(strsplit(x, "")))[ranks]
ifelse(grepl("J", x) & names(which.max(tab)) != "J", gsub("J", names(which.max(tab)), x),
ifelse(grepl("J", x), gsub("J", names(sort(tab)[1]), x), x))
})
convert <- function(x){
type.convert(gsub("A", 14,
gsub("K", 13,
gsub("Q", 12,
gsub("J", 1,
gsub("T", 10, x))))), as.is = TRUE)
}
hands$hand <- lapply(strsplit(hands$cards, ""), convert)
hands$joker_hand <- lapply(strsplit(hands$with_joker, ""), convert)
hands$hand_rank <- sapply(hands$joker_hand, function(x){
ifelse(length(which(table(x)==5)), 7,
ifelse(length(which(table(x)==4)), 6,
ifelse((max(table(x))==3 & min(table(x))==2), 5,
ifelse((max(table(x))==3 & min(table(x))<2), 4,
ifelse(sum(table(x)==2)==2, 3,
ifelse(sum(table(x)==2)==1, 2, 1))))))
})
hands <- cbind(hands[, c("bid", "hand", "joker_hand", "hand_rank")], do.call(rbind, hands$hand))
hands <- hands[order(hands[,4], hands[,5], hands[,6], hands[,7], hands[,8], hands[,9], decreasing = FALSE), ]
hands$final_rank <- seq_along(hands[,1])
hands$winnings <- hands$bid*hands$final_rank
sum(hands$winnings)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment