Day 2

Author

Julia Romanowska

Data

We have a special coding here - let’s write a dictionary for that:

  • opponents codes:
A = "rock", B = "paper", C = "scissors"
  • my codes:
X = "rock", Y = "paper", Z = "scissors"

..but the important thing is that each of these give various points, which we can basically treat as factor-levels:

(games_in <- read_delim(
  here("DATA", "2022", "input_day_02.txt"),
  delim = " ",
  col_names = FALSE,
  skip_empty_rows = FALSE,
  show_col_types = FALSE
))
# A tibble: 2,500 × 2
   X1    X2   
   <chr> <chr>
 1 C     Y    
 2 A     Z    
 3 B     Y    
 4 A     Z    
 5 A     X    
 6 A     Z    
 7 B     Y    
 8 A     Z    
 9 B     Y    
10 C     Z    
# ℹ 2,490 more rows
games_fct <- games_in %>%
  rename(opponent = X1, me = X2) %>%
  mutate(across(.fns = as.factor))
Warning: There was 1 warning in `mutate()`.
ℹ In argument: `across(.fns = as.factor)`.
Caused by warning:
! Using `across()` without supplying `.cols` was deprecated in dplyr 1.1.0.
ℹ Please supply `.cols` instead.

Explore

skimr::skim(games_fct)
Data summary
Name games_fct
Number of rows 2500
Number of columns 2
_______________________
Column type frequency:
factor 2
________________________
Group variables None

Variable type: factor

skim_variable n_missing complete_rate ordered n_unique top_counts
opponent 0 1 FALSE 3 B: 991, C: 795, A: 714
me 0 1 FALSE 3 Y: 1178, Z: 771, X: 551
levels(games_fct$opponent)
[1] "A" "B" "C"
levels(games_fct$me)
[1] "X" "Y" "Z"

✔️ OK, no missingness and no strange values.

Check who wins per round

I get 0 if I lose, 3 if it’s a draw, and 6 if I win.

#' returns points for player1
check_rules <- function(player1, player2){
  player1_lose <- 0
  player1_draw <- 3
  player1_win <- 6

  all_diff <- player1 - player2
  map_dbl(all_diff, function(cur_diff){
    if(cur_diff == 0){ # draw
      return(player1_draw)
    }
    
    if(abs(cur_diff) == 2){ # one of them has 'rock', one 'scissors'
      if(cur_diff < 0){
        return(player1_win)
      }
      
      return(player1_lose)
    }
    
    if(cur_diff > 0){ # check who has higher value
      return(player1_win)
    }
    
    return(player1_lose)
  })
}

(games_fct <- games_fct %>%
  mutate(points = check_rules(as.numeric(me), as.numeric(opponent))))
# A tibble: 2,500 × 3
   opponent me    points
   <fct>    <fct>  <dbl>
 1 C        Y          0
 2 A        Z          0
 3 B        Y          3
 4 A        Z          0
 5 A        X          3
 6 A        Z          0
 7 B        Y          3
 8 A        Z          0
 9 B        Y          3
10 C        Z          3
# ℹ 2,490 more rows

Get total points

In addition to points gained by drawing or winning a round, I get points for what I chose (levels of factor).

total_score <- games_fct %>%
  mutate(total_per_round = as.numeric(me) + points) %>%
  summarise(grand_total = sum(total_per_round))

The total score is 10941!