2023 - day 04

Author

Hendrik Wagenseil

head(txt)
[1] "Card   1: 44 22 11 15 37 50  3 90 60 34 | 35 60 76  3 21 84 45 52 15 72 13 31 90  6 37 44 34 53 68 22 50 38 67 11 55"
[2] "Card   2: 42 14 40 24 51 49 47 73 34 74 | 40 22 48 65 34 81 24 97 14 49  1 98 66 42 71 74 28 11 47  3 45 63 73 51 87"
[3] "Card   3: 16 48 80 51 41 87 46 77 23  8 | 10 77 41 46  8 36 85 16 87 27 97 13 15 35 45 80 63 37 29 60 48 51 82 61 23"
[4] "Card   4: 82 88 65 64 33 89 23 49 11 92 | 11 33 91 15 81 44 29 27 63 23  1 13 74 89 88  8 37 22 51 92 65  7 49 82 64"
[5] "Card   5: 36 61 30 42 64 45 80 26 84 60 | 50 46 76  4 12 32 38 23 36 45 44 61 53 94 37 33 11 82 84 87 26 19 93 15 98"
[6] "Card   6: 75 63 86 49 17 26 59 70 18 57 | 87  3  2 47 65 21 24 74 28 17 34 33 16 29 63 14 60 95 83 15 41 70 56 49 23"

Count the number of winning cards \(w\) and return a score \(s\), defined as \[s=\begin{cases} 0, \text{ if } w = 0 \\ 2^{w-1}, \text{ if } w > 0 \end{cases}\]

matches = function(x){
  
  spl = strsplit(x, split = "\\|")[[1]]
  pairs = lapply(
    1:2
    , FUN = \(i){
      strsplit(spl[i], split = " ")[[1]] |> 
        as.integer() |> 
        na.omit()
    }
  )
  
  sum(pairs[[2]] %in% pairs[[1]])
  
}

txt = gsub("^.*?:", "", txt) 

m = Map(
  matches
  , x = txt
) |> 
  unname() |> 
  unlist() 

sum(2^(m[m>0] -1L))
[1] 21105

Add \(m\) successive cards where \(m\) is the number of matches in a card. Get the final number of cards.

move = function(
    x
    , deck
){
  if (x > 0){
    idx = as.integer(names(x))
    from = min(length(deck), idx + 1L)
    to = min(length(deck), idx + x)
    deck[from:to]
  }
}

play = function(
    game
    , deck
){

  i = 0L
  
  # while (length(game) > 0L){
  #   new = move(game[1L], deck = deck)
  #   game = c(game[-1L], new)
  #   i = i + 1L
  #   print(i)
  # } 
  
  return(i)
  
  # if (length(game) > 0L){
  #   new = move(game[1L], deck = deck)
  #   game = c(game[-1L], new)
  #   play(game, deck = deck)
  # } else {
  #   return(idx)
  # }
    
}

names(m) = 1:length(m)
names(deck) = 1:length(m)
play(m[1], deck = m)
game = m[1:2]


addcards = function(x, org){
  
  lapply(
    1:length(x)
    , FUN = \(i){
      i = 1
      if (x[i] > 0) {
        idx = as.integer(names(x[i]))
        org[(idx+1):(idx+org[idx])]
      }
    }
  ) |> 
    unlist()
  
  if (length(x) > 0){
    return(addcards(x, org = org))
  } else {
    return(c(org, x))
  }
  
}

names(m) = 1:length(m)
org = m
x = m
addcards(m, org = m)