0

I have to create a function in R where the program picks a number between 1 and 100 and asks the user to guess. If it is too low it returns "too low" if its too high I return "too high" if after 7 guesses the user is still wrong I stop the function.

I made the function but cannot find a way to stop it after 7 times!! I want to place a for loop but dont know where can anyone help me?

guess <- function(g) {
  ran <- sample(1:100, 1)
  if (g < ran) {
    print("Too low")
    m <- readline("Type number again:")
    num <- as.numeric(m)
  } else if (g > ran) {
    print("Too high")
    m <- readline("Type number again:")
    num <- as.numeric(m)
  } else if (g == ran) {
    print("Correct")
  }
}
  • What have you tried to get to that "seven times"-requirement? There is no code given to check for this – Nico Haase Mar 08 '19 at 09:13
  • Use a `counter` which is initialized (`counter <- 0`) before you call the `sample()`, then wrap your `if` in a `while()` loop, and update the `counter <- counter + 1` after each `readLine` – RLave Mar 08 '19 at 09:24
  • Exit the loop after `counter > 7`. While loop in R: https://stackoverflow.com/questions/4357827/do-while-loop-in-r. You might have to rethink your function. – RLave Mar 08 '19 at 09:25
  • Use a `for` loop and `break` out of it if the user is right. – Roland Mar 08 '19 at 09:30

1 Answers1

0

Here is a stab at it:

guess <- function(g) {
  counter <- 1
  ran <- sample(1:100, 1)
  while(counter < 8) {
    if (g < ran) {
      print(paste0("Too low (No. of attempts: ", counter, ")"))
      m <- readline("Type number again:")
      g <- as.numeric(m)
      counter <- counter + 1
    } else if (g > ran) {
      print(paste0("Too high (No. of attempts: ", counter, ")"))
      m <- readline("Type number again:")
      g <- as.numeric(m)
      counter <- counter + 1
    } else if (g == ran) {
      print("Correct")
      opt <- options(show.error.messages=FALSE)
      on.exit(options(opt))
      stop()
    }
  }
  print(paste0("You've run out of attempts! Correct answer was: ", ran))
}

This approach does what you want by setting a counter and using a while loop to allow for seven attempts. If this number is exceeded, the loop is exited and a corresponding error message displayed. I've also added some textual information after each attempt and in the event of failure for convenience.

tifu
  • 1,352
  • 6
  • 17