I am trying to solve an exercise on Fibonacci sequences in R. The crux is that the animals are mortal. Goal is to enter 3 variables (life span, overall duration, number of offspring). The animals need 1 time unit to mature. To solve this, I create a matrix with a timer in the first row, the number of couples of offspring in the second row, then the mature couples, then the sum of offspring and mature couples. I take into account the mortality by substracting from the mature animals the number of animals that were born "i" months ago (i = life span)
vec <- vector()
wabbits3 <- function(i,k,l) {
wabbits3_chabo(i,k,l,1,0, vec, 1, i)
}
wabbits3_chabo <- function(i,k,l,m,n,t,o,p){
if (k == 0) {print(t)}
else if (p == 1) {wabbits3_chabo(i, (k-1), l,
((n+m-(t[2,(ncol(t)-i+1)]))*l),
(n+m-(t[2,(ncol(t)-i+1)])),
cbind(t, c((o),
(m),
(n),
(m+n))),
(o+1),
1)}
else {wabbits3_chabo(i, (k-1), l,
(n*l),
(n+m),
cbind(t, c((o),
(m),
(n),
(m+n))),
(o+1),
(p-1))}
}
Now, to the actual question: if I test the numbers: wabbits3(365, 6, 1)
, it never enters the else if branch as it never reaches p = 1, and everything works fine.
But, when choosing smaller numbers (wabbits3(3, 6, 1)
), it enters the else if
branch, and the addition "(m+n)
" doesnt work anymore.
The cbind
command is exactly the same in the "if
" and "else if
" branch, so why doesnt it work both times?
Result of wabbits3(365, 6, 1)
:
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 1 2 3 4 5 6
[2,] 1 0 1 1 2 3
[3,] 0 1 1 2 3 5
[4,] 1 1 2 3 5 8
(the sum of the second and third row, displayed in the fourth row works)
Result of wabbits3(3, 6, 1)
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 1 2 3 4 5 6
[2,] 1 0 1 4 5 6
[3,] 0 1 1 4 5 6
[4,] 1 1 2 4 5 6
(the addition of the second and third row doesnt work anymore, once it enters the else if
branch(in the fourth column))
Is my issue understandable? Anything unclear? Thanks in advance!
PS.: I am sure that there are others mistakes in my code, but I´d prefer finding those myself. Right now I´m simply baffled why sth as simple as an addition isnt working...
EDIT: Turns out that simply using rbind (in both branches of course) seems to fix the issue... But why?!