2

I have a recursive function(see code), if i start with depth 5

When branch

execute(depth-1,x,y,width/2,height/2);

finishes, depth is not 5 for

execute(depth-1,midX,y,width/2,height/2);

but 1, and it produces mess. You can see algorithm here: http://jsfiddle.net/g4p66/

It supposed to produce something that looks like a maze(a poorly designed maze, hah)

    function execute(depth,x,y,width,height){
        if(depth > 0){
            var midX = (x+width)/2;
            var midY = (y+height)/2;
            c.save();
            c.beginPath();
            c.moveTo(midX,midY);
            var from = Math.floor(Math.random()*4);
            if(from === 0){
                c.lineTo(midX,y);
            } else if(from === 1){
                c.lineTo(x+width,midY);
            } else if(from === 2){
                c.lineTo(midX,y+height);
            } else if(from === 3){
                c.lineTo(x,midY);
            }
            c.stroke();
            c.restore();
            execute(depth-1,x,y,width/2,height/2);
            console.log(depth);
            execute(depth-1,midX,y,width/2,height/2);
            execute(depth-1,x,midY,width/2,height/2);
            execute(depth-1,midX,midY,width/2,height/2);
        }
    }

EDIT: I was reading console.log wrongly, so it got me confused. The main reason is my midX midY calculation was wrong, should be:

var midX = (x+(x+width))/2;
var midY = (y+(y+height))/2;
1
  • i don't understand the question, what is wrong, my jsfiddle isn't working Commented Jun 2, 2014 at 9:24

1 Answer 1

2

You don't have a variable scope problem but a problem of logic in interpreting the log.

The first console.log you see isn't the one at the top level of the recursion but the one at the deepest level, because that's the execution order.

Here's what happens :

execute(5)
   execute(4)
      execute(3)
         execute(2)
            execute(1)
                execute(0) : depth <=0 -> return
            console.log(depth) -> logs 1

You can check on your own screeshot that you're deep in the recursion when you get to the log :

enter image description here

Sign up to request clarification or add additional context in comments.

2 Comments

Its not the problem, the problem is this: puu.sh/9bDFH/00d235f406.png As you can see, the depth is 1 and not 4 right after the first execute brach is finished
Look at the call stack on the right of your screenshot : you're deep into the recursion, not at the top level.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.