The 12 R functions of Xmas pt3/6

Now that we’re at day three, you hopefully know the drill (if not, check out the first of these posts). I wrote 12 small and simple R functions, basically just for a bit of fun and I’m sharing them here to spread the fun around a little.

Today’s functions are a number guessing game that reads user input and a function that tries to make us feel like we’ve been sucked into a retro sci-fi movie!

What number am I thinking of?

Time for another game. This one thinks of a number and makes you guess until you get it right. After it’s “thought” of a number it enters an infinite while-loop where it keeps asking for your guess and checking your guess against the number it thought of. The while is broken when the guess is neither higher nor lower than the internal number - in others words, when they match.

what_number <- function(){
  cat("Guess what number I'm thinking of (1-20)...\n")
  game_num <- sample(1:20, 1)
  while (TRUE){
    guess_num <- as.numeric(readline(prompt = "What's your guess? "))

    if (guess_num > game_num){
      cat("Too high!\n")
    } else if (guess_num < game_num){
      cat("Too low!\n")
    } else {
      cat("You guessed it! Well done.\n")
      break
    }
  }
}

Guess the number

Some ideas for modifications and improvements:

  • input validation - currently the function errors if non-numeric input is received
    • lack of input validation is something of a theme with many of these functions
  • Record and display the number of guesses it takes to get the right answer
  • Guess for things other than just numbers, eg. fruits
  • 2 player?

Sci-fi terminal

Christmas is a time when many of us choose to relax with a good film. I’m a big fan of science fiction, particularly older gems like Colossus: The Forbin Project. Depictions of computers in these films were very much rooted in the era and they often feature terminals that print a character at a time to the screen when printing text.

Our next function attempts to bring some of that retro-sci-fi magic to your R session.

The input message is displayed one character at a time with a default pause between each of 0.1 seconds. The speed is configurable via the ‘speed’ parameter.

terminal <- function(msg = "", speed = 1){
  speed <- 0.1 * speed
  exploded_msg <- strsplit(msg, "")
  for (single_char in exploded_msg[[1]]){
    cat(single_char)
    Sys.sleep(speed)
  }
  cat("\n")
}

Run it with some text for input and you too can pretend you’ve travelled back to the 70’s.

Incoming transmission&hellip;

Note: I turned it into a little command line application for the above gif.

Ideas for mods and improvements:

  • The best thing to do with this one would be to modify it so it could be used as a drop-in replacement for R’s cat() function
  • Configurable text colours

This marks the halfway point of this little series, only three more posts to go. So, pop back tomorrow for some more (mostly pointless) functions!