Bulls and cows/Player: Difference between revisions
Content added Content deleted
ReeceGoding (talk | contribs) m (→{{header|R}}: Improved syntax.) |
ReeceGoding (talk | contribs) m (→{{header|R}}) |
||
Line 2,941: | Line 2,941: | ||
repeat |
repeat |
||
{ |
{ |
||
remainingCasesCount <- |
remainingCasesCount <- nrow(validGuesses) |
||
cat("Possibilities remaining:", remainingCasesCount)#Not required, but excellent when debugging. |
cat("Possibilities remaining:", remainingCasesCount)#Not required, but excellent when debugging. |
||
guess <- validGuesses[sample(remainingCasesCount, 1), ] |
guess <- validGuesses[sample(remainingCasesCount, 1), ] |
||
Line 2,948: | Line 2,948: | ||
if(bulls == 4) return(paste0("Your number is ", guessAsOneNumber, ". I win!")) |
if(bulls == 4) return(paste0("Your number is ", guessAsOneNumber, ". I win!")) |
||
cows <- as.integer(readline("Cow score? [0-4] ")) |
cows <- as.integer(readline("Cow score? [0-4] ")) |
||
⚫ | |||
#If our guess scores y bulls, then only numbers containing exactly y digits with the same value and position (y "pseudoBulls") as in our guess can be correct. |
#If our guess scores y bulls, then only numbers containing exactly y digits with the same value and position (y "pseudoBulls") as in our guess can be correct. |
||
#Accounting for the positions of cows not being fixed, the same argument also applies for them. |
#Accounting for the positions of cows not being fixed, the same argument also applies for them. |
||
Line 2,954: | Line 2,953: | ||
#We also use pseudoBulls != 4 to remove our most recent guess, because we know that it cannot be correct. |
#We also use pseudoBulls != 4 to remove our most recent guess, because we know that it cannot be correct. |
||
#Finally, the drop=FALSE flag is needed to stop R converting validGuesses to a vector when there is only one guess left. |
#Finally, the drop=FALSE flag is needed to stop R converting validGuesses to a vector when there is only one guess left. |
||
⚫ | |||
isGuessValid <- function(x) pseudoBulls(x) == bulls && sum(x %in% guess) - pseudoBulls(x) == cows && pseudoBulls(x) != 4 |
isGuessValid <- function(x) pseudoBulls(x) == bulls && sum(x %in% guess) - pseudoBulls(x) == cows && pseudoBulls(x) != 4 |
||
validGuesses <- validGuesses[apply(validGuesses, 1, isGuessValid), , drop = FALSE] |
validGuesses <- validGuesses[apply(validGuesses, 1, isGuessValid), , drop = FALSE] |
||
if( |
if(nrow(validGuesses) == 0) return("Error: Scoring problem?") |
||
} |
} |
||
} |
} |