I am working with the R programming language. I am trying to learn more about WHILE LOOPS and thought of the following problem to implement them in:
- Step 1: Keep generating 3 random numbers until the sum of these 3 numbers is > 150
- Step 2: Save the results from Step 1 and the number of times you had to generate these numbers until the condition was met
- Step 3 : Repeat Step 1 - Step 2 for 100 turns
I tried to do this like this:
num_1_i = num_2_i = num_3_i = 0
list_results <- list()
for (i in 1:100)
{
while (num_1_i num_2_i num_3_i < 150) {
turn_i = i
num_1_i = runif(1,0,100)
num_2_i = runif(1,0,100)
num_3_i = runif(1,0,100)
break
}
inter_results_i <- data.frame(turn_i, num_1_i, num_2_i, num_3_i)
list_results[[i]] <- inter_results_i
}
This is producing the same numbers every time:
[[98]]
turn_i num_1_i num_2_i num_3_i
1 1 87.67886 32.7703 52.72885
[[99]]
turn_i num_1_i num_2_i num_3_i
1 1 87.67886 32.7703 52.72885
[[100]]
turn_i num_1_i num_2_i num_3_i
Can someone please show me what I am doing wrong and how to fix this?
Thanks!
Note: Alternate Method I tried - still doesn't work:
list_results <- list()
for (i in 100) {
repeat {
turn_i = i
num_1_i = runif(1,0,100)
num_2_i = runif(1,0,100)
num_3_i = runif(1,0,100)
if(num_1_i num_2_i num_3_i < 150) break
}
results_tmp <- data.frame(turn = i, num_1 = num_1_i, num_2 = num_2_i, num_3 = num_3_i)
list_results[[i]] <- results_tmp
}
CodePudding user response:
Lets check your code:
while (num_1_i num_2_i num_3_i < 150) {
turn_i = i
num_1_i = runif(1,0,100)
num_2_i = runif(1,0,100)
num_3_i = runif(1,0,100)
break >>>> LOOK AT HERE! YOUR LOOP WILL WORK ONLY ONE TIME AND BREAKS HERE
}
And there is some difference between WHILE and REPEAT loops:
In WHILE loops the criteria(s) is/are checked in the begining of the loop, and if it returns TRUE, code block will run, in this situation maybe your code is not working fine! But in REPEAT loops, code block will run at least one time! look at here:
repeat{
num_1_i = runif(1,0,100)
num_2_i = runif(1,0,100)
num_3_i = runif(1,0,100)
if(num_1_i num_2_i num_3_i < 150){
break
}
}
In my opinion, you should use REPEAT in this case.
Good luck!
CodePudding user response:
It is because after finding the first combination that exceeds 150 you don't reset the numbers back to 0. So it never enters the while
loop again and the same numbers are stored 100 times.
Simply move the first line of setting numbers to 0 into the for loop:
list_results <- list()
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 < 150) {
turn_i = i
num_1_i = runif(1,0,100)
num_2_i = runif(1,0,100)
num_3_i = runif(1,0,100)
break
}
inter_results_i <- data.frame(turn_i, num_1_i, num_2_i, num_3_i)
list_results[[i]] <- inter_results_i
}