0

Recursion / Sierpinsky

Hello all, so i am a bit confused with the code i have posted below which creates a sierpinsky triangle. How is it that this code works when the code that actually draws something isnt called until limit reaches 0? <script> var can = document.getElementById("can"); var c = can.getContext('2d'); can.width = window.innerWidth; can.height = window.innerHeight; c.translate(can.width/2,can.height/2 + 50) var p0 = { x: 0, y: -301 }, p1 = { x: 258, y: 140 }, p2 = { x: -258, y: 140 }; sierpinski(p0, p1, p2, 8); function sierpinski(p0, p1, p2, limit) { if(limit > 0) { var pA = { x: (p0.x + p1.x) / 2, y: (p0.y + p1.y) / 2 }, pB = { x: (p1.x + p2.x) / 2, y: (p1.y + p2.y) / 2 }, pC = { x: (p2.x + p0.x) / 2, y: (p2.y + p0.y) / 2 }; sierpinski(p0, pA, pC, limit - 1); sierpinski(pA, p1, pB, limit - 1); sierpinski(pC, pB, p2, limit - 1); } else { drawTri(p0, p1, p2); } } function drawTri(p0,p1,p2) { c.beginPath(); c.moveTo(p0.x,p0.y); c.lineTo(p1.x,p1.y); c.lineTo(p2.x,p2.y); c.fill() }

6th May 2020, 7:19 PM
Chad Williams
Chad Williams - avatar
1 Resposta
+ 1
The sierpinski function calls 3 versions of itself on each call. So we can conclude that some of the various versions of the sierpinski function calls drawTri. You can imagine that behavior as a tree. The root is the first call(from outside) to the sierpinski function. The drawTri function is called by the leaf nodes. Those leaves nodes are the versions of sierpinski that reach limit 0.
7th May 2020, 10:14 PM
Kevin ★