Quotes help make search much faster. Example: "Practice Makes Perfect"

Sunday, December 9, 2012

Codecademy: Codeyear Unpacking the stack, Part 2


//sample solution


var stack = [];

function countDown(int) {
  stack.push(int);
  if (int === 1) {
    return 1;
  }
    return countDown(int - 1);
}

function multiplyEach() {
  // Remove the last value of the stack
  // and assign it to the variable int
  int = stack.pop();
  x = stack.length;
  // Base case
  if (x === 0) {
    return 1;
  }
  // Recursive case
  else {
stack[x - 1] = int * stack[x - 1];
multiplyEach();
return int;
  }
}

// Call the function countDown(7)
countDown(10);
console.log(stack);
// And then print out the value returned by multiplyEach()
console.log(multiplyEach());

3 comments:

  1. The code you have above doesn't work. At least not in CodeAcademy. Tried the below instead and it worked:

    var stack = [];

    function countDown(int) {
    stack.push(int);
    if (int === 1) {
    return 1;
    } else {
    return countDown(int - 1);
    }
    }

    function multiplyEach() {
    // Remove the last value of the stack
    // and assign it to the variable int
    int = stack.pop();
    x = stack.length;
    // Base case
    if ( x === 0) {
    return int;
    } else {
    stack[x - 1] = int * stack[x - 1];
    return multiplyEach();
    }
    }

    // Call the function countDown(7)
    countDown(7);
    console.log(stack);
    // And then print out the value returned by multiplyEach()
    console.log(multiplyEach());

    ReplyDelete


This is an example of scrolling text using Javascript.

Popular Posts