Number of iteration in for loop

Here,
I am trying to store the number of iterations and random numbers for a given number(total).
In this code, I used n=10 for taking the random numbers(positive) of 50 till it reaches <=3 (the differences).
I want to store the value upto the iteration that fulfills the condition as well as the difference of the last step.

n=10
m=matrix(NA,nrow=n,ncol=2)
total=50
for (i in 1:n){
a <- runif(1, 0, total)
m[i,1]=i
m[i,2]=a
total_new=total-a
total=total_new
if (total_new <= 3){
  break
}
}
m

Expected outcome:

Here, set.seed is just for the easier view of what I am expecting.

set.seed(100)
n=10
m=matrix(NA,nrow=n,ncol=2)
total=50
for (i in 1:n){
  a <- runif(1, 0, total)
  m[i,1]=i
  m[i,2]=a
  total_new=total-a
  total=total_new
  if (total_new <= 3){
    break
  }
}

m[7,]=c(7,50-sum(m[1:6,2]))
m[1:7,]
set.seed(100)
n=10
m=matrix(NA,nrow=n,ncol=3)
total=50
for (i in 1:n){
  a <- runif(1, 0, total)
  m[i,1]<-i
  m[i,2]<-a
  total<-total-a
  m[i,3]<- total

  if (total <= 3){
    break
  }
}
m

Thanks @nirgrahamuk for your prompt reply.
However, the result is not what I am expecting.
Here, n=10 is just for an example. I will be grateful if you can try to find how to get the value of n as well as similar output as provided above without using set.seed.


m=matrix(NA,nrow=1,ncol=3)
total=50
i<-0
while (TRUE){
  i<-i+1
  a <- runif(1, 0, total)
  m[i,1]<-i
  m[i,2]<-a
  total<-total-a
  m[i,3]<- total
  
  if (total <= 3){
    break
  }

  m <- rbind(m,matrix(NA,nrow=1,ncol=3))
}
m
(n<-dim(m)[[1]])
1 Like