2023 - day 07

Author

Hendrik Wagenseil

Rank hands of cards and get the total winnings (bid * rank).

head(txt, n = 12L)
 [1] "9A35J 469" "75T32 237" "6T8JQ 427" "3366A 814" "K2AK9 982" "J8KTT 9"  
 [7] "94936 970" "Q8AK9 15"  "3QQ32 940" "65555 484" "8K88K 674" "Q67T5 788"
types = c(
  "11111" = "1_highcard"
  , "1112" = "2_onepair"
  , "122" = "3_twopair"
  , "113" = "4_threeofakind"
  , "23" = "5_fullhouse"
  , "14" = "6_fourofakind"
  , "5" = "7_fiveofakind"
)

values = c(
  "A" = 14
  , "K" = 13
  , "Q" = 12
  , "J" = 11
  , "T" = 10
  , "9" = 9
  , "8" = 8
  , "7" = 7
  , "6" = 6
  , "5" = 5
  , "4" = 4
  , "3" = 3
  , "2" = 2
)

handtable = function(x){
  table(x) |> 
    sort() |> 
    paste(collapse = "")
}

handtype = function(x, typ = types){
  
  h = strsplit(x, split = "")
  h = Map(
    handtable
    , x = h
  ) |> 
    unlist()
  
  typ[
    match(
      h
      , table = names(typ)
    )
  ] |> 
    unname()
  
}

secondorder = function(x, val = values){
  
  h = strsplit(x, split = "")
  h = lapply(
    h
    , FUN = \(i) {
      unname(
        val[
          match(
            i
            , table = names(val)
          )
        ]
      )
    }
  )
  
  lapply(
    h
    , FUN = \(i) {
      as.numeric(
        (i / 10) %*% c(100000000, 1000000, 10000, 100, 1)
      )
    }
  ) |> 
    unlist()
  
}

data = data.table(
  txt = txt
)

data[, hand := tstrsplit(txt, split = " ", keep = 1L)]
data[, score := tstrsplit(txt, split = " ", keep = 2L)]
data[, score := as.integer(score)]
data[, type := handtype(hand)]
data[, sorder := secondorder(hand)]

setorder(data, type, sorder)

data[, rank := .I]
data[, bid := rank * score]
sum(data$bid)
[1] 250120186
head(txt, n = 12L)
 [1] "9A35J 469" "75T32 237" "6T8JQ 427" "3366A 814" "K2AK9 982" "J8KTT 9"  
 [7] "94936 970" "Q8AK9 15"  "3QQ32 940" "65555 484" "8K88K 674" "Q67T5 788"