- Solve simple problems
- Decomposition
- Pattern matching
- Abstraction
- Systems Analysis
- Identify the system parts and processes
- Use R to simulate a system
- See what happens in the long term
- See the effect of changing rates or initial conditions
May 12, 2020
We know that Computational Thinking has four parts
Today we will talk about patterns
When we see a pattern we can make
There is another kind of pattern
Sometimes the easiest way to define a pattern is to use the same pattern.
For example:
To represent these patterns we use functions that are part of themselves
example<-function(input) { code example(data) code return(output) }
One useful mathematical function is factorial
The factorial of a \(n\) is \(n!\), defined as \[n! = n\cdot(n-1)!\]
That is, the factorial of n
is n
times the factorial of n-1
How do we write it in R?
factorial <- function(n) { ans <- n * factorial(n-1) return(ans) }
There is an error here. Can you find it?
Use the debugger to see what is happening
Each recursive function needs an exit condition
That is, some rule to decide when to finish
There is always an easy case that does not require recursion
For example, the factorial of 1 is \(1! = 1\).
factorial <- function(n) { if(n <= 1) { ans <- 1 } else { ans <- n * factorial(n-1) } return(ans) }
find_min <-function(vector) { n <- length(vector) if(n==1) { return(vector[1]) } else { a <- find_min(vector[1:(n/2)]) b <- find_min(vector[(n/2+1):n]) if(a<b) { return(a) } else { return(b) } } }
tree <- function(level) { save turtle position if(level<=1) { draw branch } else { tree(level-1) } recover turtle position }
“In order to understand recursion, one must first understand recursion.”
How Recursion Works — explained with flowcharts and a video
Exercise: Homework from previous year