Hello,
I have a question about the behavior of the increment/decrement operator in recursive functions.
Here’s a tree fractal pattern:
function setup() {
...
angleMode(DEGREES);
}
function draw() {
...
drawBranch(width/2, height,0, 3);
}
function drawBranch(x, y, agl, n){
let x1 = x - 50*sin(agl);
let y1 = y - 50*cos(agl);
line(x, y, x1, y1);
if(n > 1){
drawBranch(x1, y1, agl-30, n--);
drawBranch(x1, y1, agl+30, n--);
}
}
Instead of a symmetrical tree, using n--
results in an issue where the branches are not drawn symmetrically, as shown here:
I fixed this by explicitly using n - 1
instead of n--
in the recursive calls:
function drawBranch(x, y, agl, n){
...
if(n > 1){
drawBranch(x1, y1, agl-15, n-1);
drawBranch(x1, y1, agl+15, n-1);
}
}
With this change, the tree is drawn correctly. Could anyone explain why the n--
caused this issue in the first place?
Thanks !