Description Usage Arguments Value Author(s) Examples
Takes in the bounds used for the random number generation and then asks for the user to guess the random number.
1 | randomNumberGame(leftbound, rightbound)
|
leftbound |
The least value that the random number can hold |
leftbound |
The greatest value that the random number can hold |
Has a void return type. Prints out the results instead of returning them
Matt Heffernan, University of Illinois at Chicago
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | randomNumberGame(1,10)
Generates a random number between 1 and 10 inclusive and asks for the user to guess it
##---- Should be DIRECTLY executable !! ----
##-- ==> Define data, use random,
##-- or do help(data=index) for the standard data sets.
## The function is currently defined as
randomNumberGame <- function(leftbound, rightbound){
if(leftbound > rightbound)
{
cat("Upper bound should be greater than lower bound\n")
return()
}
secretNumber<-sample(leftbound:rightbound, 1)
count <- 1
cat("Range: ",leftbound,"-",rightbound)
guess <- readline("Enter a guess : ");
guess <- as.integer(guess)
while(guess != secretNumber)
{
if(guess < leftbound || guess > rightbound)
{
cat("Your guess is outside of the valid range", leftbound,"-",rightbound,". Try Again \n")
}
else if(guess < secretNumber)
{
cat("The secret number is greater than your guess\n")
}
else if(guess > secretNumber)
{
cat("The secret number is less than your guess\n")
}
count <- count + 1
guess <- readline("Enter a guess : ");
guess <- as.integer(guess)
}
cat("You got it! The secret number is ", secretNumber,". It took you ",count," guesses")
}
|
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.