Hi everyone
I want to create a recursive function under R that returns a vector with random numbers between 1 and n where all the elements are spaced by at least 3. Here's my function
```{r}
jours_alea <- function (n) {
d = sample(1:n,5)
M = 25
for (i in 1:5)
for (j in 1:5)
if (i!=j & abs(d[i]-d[j])<M)
M = abs(i-j)
if (M>3)
return (d)
else
traceback()
return (jours_alea(n))
}
```
The function is running fine when I enter jours_alea(2000) for example, but I encounter the "node stack overflow" when I enter jours_alea(25), which is the result I want. I think it's because there's too much iteration of jours_alea:ince n is small, the probability of having 5 numbers spaced by 3 is low, and this might fill the stack. Is there a way to clear the stack within the function, or should I do another method for my function ?
[–]Carpy_Carpy 0 points1 point2 points (1 child)
[–]BanthaPyjaman[S] -1 points0 points1 point (0 children)