bullsAndCowsPlayer <- function()
{
  guesses <- 1234:9876
  
  guessDigits <- t(sapply(strsplit(as.character(guesses), ""), as.integer))
  validGuesses <- guessDigits[apply(guessDigits, 1, function(x) length(unique(x)) == 4 && all(x != 0)), ]
  repeat
  {
    remainingCasesCount <- nrow(validGuesses)
    cat("Possibilities remaining:", remainingCasesCount)
    guess <- validGuesses[sample(remainingCasesCount, 1), ]
    guessAsOneNumber <- as.integer(paste(guess, collapse = ""))
    bulls <- as.integer(readline(paste0("My guess is ", guessAsOneNumber, ". Bull score? [0-4] ")))
    if(bulls == 4) return(paste0("Your number is ", guessAsOneNumber, ". I win!"))
    cows <- as.integer(readline("Cow score? [0-4] "))
    
    
    
    
    
    pseudoBulls <- function(x) sum(x == guess)
    isGuessValid <- function(x) pseudoBulls(x) == bulls && sum(x %in% guess) - pseudoBulls(x) == cows && pseudoBulls(x) != 4
    validGuesses <- validGuesses[apply(validGuesses, 1, isGuessValid), , drop = FALSE]
    if(nrow(validGuesses) == 0) return("Error: Scoring problem?")
  }
}
bullsAndCowsPlayer()