Hi,
I spent the entire day yesterday eating strawberries, drinking a strawberry smoothie, nibbling on strawberry pie and waiting for inspiration (Iβm pretty sure my blood is red due to anthocyanins at this pointπ). I only had to alter my routine from time to time, because every hour or so, one of the four cats my family is looking after wanted to be fed. And since some of them are strays, I thought I could demonstrate something called a recursive function β and why it's important to neuter feral cats β all in one go.
I like to think of recursive functions as similar to what happens when you try to share your screen on Teams and, for a second, you see your screen containing your screen containing your screen... Basically, a recursive function is a function that calls itself.
Now, letβs look at the cats. Cats can also contain cats that in the future can contain cats which in the future canβ¦
Weβll start with one female cat. The assumptions are:
Every year, each female cat gives birth to 4 kittens, 2 of which are female.
Each new female becomes fertile the next year.
All cats give birth once per year.
Cats do not die.
For simplicity, weβll only count the number of female cats after a given number of years:
count_cats <- function(years) {
if (years == 0) {
return(1) # Start with 1 female cat
} else {
prev_year_cats <- count_cats(years - 1)
return(prev_year_cats + 2 * prev_year_cats) # Each mother has 2 daughters
}
}
It always helps me to do a couple of first calculations by hand to see how things work. When you are done with this part, letβs see what would happen after 5 years:
for (i in 0:5) {
cat("Year", i, "->", count_cats(i), "female cats\n")
}
I hope that it convinced you about the importance of recursive functions and neutering poor kittens.
Ciao,
Agnes
PS: Here is the survey in which you can tell me what R topic you find particularly confusing and why you want to learn it so that we can shape this space together!