Rock, Paper, Scissors, Lizard, Spock游戏R语言sheldon_game函数参数校验异常问题求助
Fixing the Parameter Validation Issue in Your Rock-Paper-Scissors-Lizard-Spock R Function
Let's break down why your current function throws errors even with valid inputs, then fix it step by step.
The Root Problem
Your sheldon_game function's loop logic is flawed:
- For every row in
dataTable, if the current row's Player-1 and Player-2 don't match your inputAandB, it immediately callsstop(). - That means even if there's a valid matching row later in the table, the loop hits a non-matching row first and crashes before finding the correct entry.
The Fix
We'll restructure the function to first validate inputs, then fetch the outcome efficiently without a problematic loop:
dataTable <- matrix(data = NA, nrow = 25, ncol = 3, byrow = TRUE) dataTable <- as.data.frame(dataTable) colnames(dataTable) <- c("Player-1", "Player-2", "Outcome") ## Fill in columns dataTable[, 1] <- c(rep("Rock", 5), rep("Paper", 5), rep("Scissors", 5), rep("Lizard", 5), rep("Spock", 5)) dataTable[, 2] <- c(rep(c("Rock", "Paper", "Scissors", "Lizard", "Spock"), 5)) # Filling In The Outcome Column: outcome_col <- c("Draw!", "Player 2 Wins!", "Player 1 Wins!", "Player 1 Wins!", "Player 2 Wins!", "Player 1 Wins!", "Draw!", "Player 2 Wins!", "Player 2 Wins!", "Player 1 Wins!", "Player 2 Wins!", "Player 1 Wins!", "Draw!", "Player 1 Wins!", "Player 2 Wins!", "Player 2 Wins!", "Player 1 Wins!", "Player 2 Wins!", "Draw!", "Player 1 Wins!", "Player 1 Wins!", "Player 2 Wins!", "Player 1 Wins!", "Player 2 Wins!", "Draw!") # Place outcome_col as third column and convert as factors: dataTable[, 3] <- as.factor(outcome_col) sheldon_game <- function(A, B){ # Define valid moves first valid_moves <- c("Rock", "Paper", "Scissors", "Lizard", "Spock") # Step 1: Validate inputs are in valid moves if (!A %in% valid_moves || !B %in% valid_moves) { stop("Parameters out of bounds! Valid moves are: Rock, Paper, Scissors, Lizard, Spock") } # Step 2: Find the matching row and return outcome match_row <- dataTable[dataTable$`Player-1` == A & dataTable$`Player-2` == B, ] res <- match_row$Outcome return(res) } # Test valid input sheldon_game("Scissors","Paper") # Should return "Player 1 Wins!" # Test invalid input sheldon_game("Scissors","Banana") # Should throw error
Key Improvements
- Explicit Input Validation: We first check if
AandBare in the list of valid moves. This catches invalid inputs immediately, before even looking at the outcome table. - Efficient Outcome Lookup: Instead of looping through every row, we use R's vectorized subsetting to directly find the row where both Player-1 and Player-2 match the inputs. This is faster and avoids the loop logic error.
- Clearer Error Message: The error message now explicitly lists valid moves to help users correct their input.
内容的提问来源于stack exchange,提问作者Iftikhar
相关产品推荐
相关产品推荐

