Home > database >  Do while loops store intermediate results?
Do while loops store intermediate results?

Time:07-04

I have the following loop that keeps generating 3 random numbers until these 3 random numbers sum to exactly 10. Then, it will repeat this process 100 times. Here is the code for this:

for (i in 1:100){
    num_1_i = num_2_i = num_3_i = 0
    
    while(num_1_i   num_2_i   num_3_i != 10){
        num_1_i = runif(1,0,5)
        num_2_i = runif(1,0,5)
        num_3_i = runif(1,0,5)
    }
    
    inter_results_i <- data.frame(i, num_1_i, num_2_i, num_3_i)
    list_results[[i]] <- inter_results_i
}

I know that this WHILE LOOP will take a very long time to run given that the WHILE condition is very "strict" (i.e. its pretty difficult to come up with 3 random numbers that sum to a specific number). Suppose I were to run this WHILE LOOP for a few hours and notice that the code is still running - if I were to "interrupt" the computer (e.g. click the "interrupt button" in R, i.e. red stop sign in the corner), I would likely loose all the "progress" I had made (e.g. suppose the computer generated 5 triples of numbers that summed to 10).

My Question: Can this while loop be altered in such a way, such that upon interruption, the "intermediate progress" is saved in the "list_results" object? I am interested in learning how to modify the general code for a WHILE LOOP such that upon interruption, the intermediate progress is saved.

Note: I would be interested to see an example of how to write any WHILE LOOP that is capable of storing intermediate results.

CodePudding user response:

Just define your list_results before the for loop as empty list if you try the following code

list_results <- list()
for (i in 1:1000){
    num_1_i = num_2_i = num_3_i = 0
    
    while(num_1_i   num_2_i   num_3_i != 150){
        num_1_i = sample(1:100 , 1)
        num_2_i = sample(1:100 , 1)
        num_3_i = sample(1:100 , 1)
    }
    
    inter_results_i <- data.frame(i, num_1_i, num_2_i, num_3_i)
    list_results[[i]] <- inter_results_i
}

and interrupt the process quickly you will find some values in list_results but not 1000 values

  • Related