0

I would like to make the same robot walk function with javascript but it get call stack size error.

http://www.chegg.com/homework-help/questions-and-answers/robot-take-steps-1-2-3-meters-write-program-allows-shows-possible-steps-robot-take-using-r-q3756383

    function walk(meter) {
        if(meter < 0) {
            count = 0;
        } else if(meter <= 2) {
            count = meter;
        } else if(meter == 3) {
            count = walk(meter-1)+walk(meter-2)+1;
        } else {
            count = walk(meter-1)+walk(meter-2)+walk(meter-3);
        }
        return count;
    }


    console.log(walk(100));
5
  • What is expected result? Commented Aug 12, 2017 at 6:34
  • The xpected output in the link is all the possible combinations to travel a given distance - however, this code outputs a single value, so is not even close to the requirement Commented Aug 12, 2017 at 6:40
  • if the answer below is correct (and it does look correct) - then your output would be 1.803963808151009e+26 lines of combinations - how much time do you have? Commented Aug 12, 2017 at 6:50
  • sorry about the misunderstanding. Yes, you are right. The variable "count" means "How many walk pattern would be to walk 100 meters" Commented Aug 12, 2017 at 7:06
  • @kphex See stackoverflow.com/help/how-to-ask Commented Aug 12, 2017 at 7:09

1 Answer 1

1

It would exceed call stack size since your complexity is exponential, you can use memoization to solve your problem which helps covert an exponential time complexity into a polynomial one, now this code runs in O(100)

	let obj = {};
	function walk(meter) {
        if(meter < 0) {
            count = 0;
        }
        else if(obj[meter] != undefined){
        	return obj[meter];
        } else if(meter <= 2) {
            count = meter;
        } else if(meter == 3) {
            count = walk(meter-1)+walk(meter-2)+1;
        } else {
            count = walk(meter-1)+walk(meter-2)+walk(meter-3);
        }
        obj[meter] = count;
        return count;
    }


    console.log(walk(100));

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

2 Comments

How do we know what expected result is?
you can try verfiying for smaller values, only OP can verify for 100 though

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.