Created
December 2, 2022 10:01
-
-
Save ozjimbob/b998167c1bc9646f4caf96218354a6a2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Data file is as provided | |
data <- read.delim("data_02.txt",header=FALSE,sep=" ") | |
# Simple lsit to look up scores for Rock/Paper/Scissors | |
scores <- list(X=1, Y=2, Z=3) | |
# Look-up matrix for win/lose/draw conditions, R/P/S in rows/columns | |
WLD <- matrix(c(3,0,6, | |
6,3,0, | |
0,6,3),nrow=3) | |
# Look up vectors, just to convert letters to 1,2,3 array indices | |
vec_home <- c("A","B","C") | |
vec_away <- c("X","Y","Z") | |
# For given home (A/B/C) and away (X/Y/Z) return total score for round | |
game_score <- function(home,away){ | |
home_idx <- which(vec_home == home) # get numeric index | |
away_idx <- which(vec_away == away) # get numeric index | |
m_score <-WLD[home_idx,away_idx] # use indices to look up score | |
m_score + scores[[away]] # add score to hand score | |
} | |
# Function to process each line of file through game_score function | |
process_round <- function(x){ | |
this_round <- data[x,] | |
game_score(this_round$V1,this_round$V2) | |
} | |
# Map file through process_round function then sum - I prefer purrr, i've forgotten the | |
# efficient way to do this in base! | |
final_score <- sum(unlist(lapply(1:nrow(data),process_round))) | |
print(final_score) | |
# Part 2- look-up matrix for given A/B/C, X/Y/Z inputs, what hand do I need to | |
# meet the plan? | |
NEW_WLD <- matrix(c("Z","X","Y", | |
"X","Y","Z", | |
"Y","Z","X"),nrow=3) | |
# Function to use the NEW_WLD matrix to tell me what hand I need | |
get_correct <- function(home,away){ | |
home_idx <- which(vec_home == home) | |
away_idx <- which(vec_away == away) | |
NEW_WLD[home_idx,away_idx] | |
} | |
# Process as before, but look up the hand I need and use it instead | |
process_round2 <- function(x){ | |
this_round <- data[x,] | |
which_hand <- get_correct(this_round$V1,this_round$V2) | |
game_score(this_round$V1,which_hand) | |
} | |
# Apply | |
final_score <- sum(unlist(lapply(1:nrow(data),process_round2))) | |
print(final_score) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment