[Write-Up] Pyramid Slide Down Solution Using JavaScript

Hi, today i want to write a write-up for one of code wars challenge. I don’t know it’s right or wrong. But yeah, this challenge, i can’t solve it alone. I following this provided code.

I really feel embarrassed for following another solution. But yeah, because of this, i write this write-up. I hope i can make a bit of understanding. Btw, i still learning too… So … los gehts!!!.

The Question

The Answer

The first line, tell us, that we build a variable named pyramidSum that has an empty array. After that, using forEach function, it takes two parameter elem and index. Oke let’s take a look, what elem and index was. So, here is them

By loging in console, we get that elem is the element of index and index is the number of index.

The empty array that had been declared before (pyramidSum) is now being pushed with the map of elem with takes parameter e. This function will only return the last index (pyramid.length - 1). The other index that is not the last index will be 0. Like this.

For make it clearer, let’s turn all the number into string like this

After understanding that, let’s begin the next part of this function, there are

This is for loop that looping through pyramidSum length — 2. The total length of that array is 15. So it will iterate through 13 array.

Inside the first loop, the second loop is established. It takes again the pyramidSum[i] length. It means, like this. If we have array [[1,2],[2,3,4],[4,5,6]]. So the [i==1] output will be [1,2]. The ‘j’ will iterate again the array of [i]. So if we iterate through the array [2][1]. It will print 5. Because the [2] means [4,5,6] and the first index of [4,5,6] is 5. I hope it easier to understand.

Next we come into the most important part, that make this function work with the solution.

I don’t really understand about that. But, at least i know, that pyramidSum will be iterated through pyramid in index [i][j], and it will be added the Math.max (largest number of two arrays) using simultaneously addition.

The log of pyramidSum is this

What i mean simultaneously is this

The array will decide will use the largest index between two value and will added into up. Until found the total of the sum. It means, the answer will be in the [0][0] index. So for the closing, this function return the pyramidSum[0][0]. And yeah it will print out the targeted value

And it’s done.

FYI, that was the solution from railsstudent. I think that was really great. But, there is more advanced solution. We can see this, if we finish this challenge. But i will give you right now, here is the most effective solution

So simple right?




Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store