Search code examples
javascriptfactorial

JS learning exercise?


So I'm just starting out teaching myself JS from a cheesy textbook and there's a challenge to figure out what this code does:

function clunk (times) {
    var num = times;
    while (num > 0) {
        display("clunk");
        num = num - 1;
    }
}

function thingamajig (size) {
    var facky = 1;
    clunkCounter = 0;
    if (size == 0) {
        display("clank");
    } else if (size == 1) {
        display("thunk");
    } else {
        while (size > 1) {
            facky = facky * size;
            size = size - 1;
        }
        clunk (facky);
    }
}

function display(output) {
    console.log(output);
    clunkCounter = clunkCounter + 1;
}

var clunkCounter = 0;
thingamajig(5);
console.log(clunkCounter);

For the life of me, I can't follow the logic here that gives the answer at the back, which is that "clunk" will display in the console 120 times. They mention it has to do with factorials (I was never any good with math...) but I can't find the step where the code to display "clunk" repeats that many times. To spare you all the details, every time I walk through it on paper/in my head I just get "clunk" 1 as the output in the console... can anyone hold my hand through this or show me where this factorial part is happening? Thanks!


Solution

  • Because aviya.developer has already shared with you how to debug the program, I'll talk to you about the algorithm. I would suggest you study up on programming fundamentals a bit more, because it seems like you might now have a good grasp on how loops work. This algorithm relies on the variables facky, and size to do the factorial calculation, which we then pass to the display method. So you can repeat that for a few iterations and you should be able to start to understand the flow of the program. The factorial part is the while loop in the thingamajig method.

    facky = facky * size;

    facky is initialized to 1, and our size is 5. The formula for a factorial can be found easily online:

    n!=n×(n−1)×(n−2)...×2×1

    5! = 5 * 4 * 3 * 2 * 1 = 120

    • Iteration 1: 1 * 5 = 5
    • Iteration 2: 5 * 4 = 20
    • Iteration 3: 20 * 3 = 60
    • Iteration 4: 60 * 2 = 120
    • Iteration 5: 120 * 1 = 120

    This is the value that we will call the function clunk with.

    clunk also has a while loop, which has a termination condition of num > 0. This means we will continue to iterate while this condition is true. Once it is no longer true, the iteration will stop.

    This means, we will call the method displaywith a value of "clunk" 120 times before the iteration ends.

    When you are analyzing an algorithm, it's important to figure out the key components/variables/operations of that algorithm, and keep track of how they change over time or through iterations. This will indicate when the end-goal is reached.