While Loops and Midpoints

Recently, I learned how to write a loop that initializes some number, and then randomly generates numbers until the initial number is guessed (while recording the number of guesses it took) such that no number will be guessed twice:

for (i in 1:100){
    guess_i = 0
    correct_i = sample(1:100, 1)
    guess_sets <- 1:100  ## initialize a set
    trial_index <- 1
    while(guess_i != correct_i){
        guess_i = sample(guess_sets, 1)  ## sample from this set
        guess_sets <- setdiff(guess_sets, guess_i)  ## remove it from the set
        trial_index <- trial_index + 1  
    ## no need to store `i` and `guess_i` (as same as `correct_i`), right?
    game_results_i <- data.frame(i, trial_index, guess_i, correct_i)
    all_games[[i]] <- game_results_i

all_games <- do.call("rbind", all_games)

I am now trying to modify the above code to create the following two loops:

  • (Deterministic) Loop 1 will always guess the midpoint (round up) and told if their guess is smaller or bigger than the correct number. They will then re-take the midpoint (e.g. their guess and the floor/ceiling) until they reach the correct number.
  • (Semi-Deterministic) Loop 2 first makes a random guess and is told if their guess is bigger or smaller than the number. They then divide the difference by half and makes their next guess randomly in a smaller range. They repeat this process many times until they reach the correct number.

I tried to write a sketch of the code:

#Loop 2:

correct = sample(1:100, 1)
guess_1 = sample(1:100, 1)
guess_2 = ifelse(guess_1 > correct, sample(50:guess_1, 1),  sample(guess_1:100, 1))
guess_3 = ifelse(guess_2 > correct, sample(50:guess_2, 1),  sample(guess_2:100, 1))
guess_4 = ifelse(guess_4 > correct, sample(50:guess_3, 1),  sample(guess_3:100, 1))

But I am not sure if I am doing this correctly.

  • Can someone please help me with this?

Thank you!

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.