Saturday, September 3, 2016

Algorithms

Algorithms are all around us. We use them everyday. Some are simple: wake up, brush teeth, shower, while some are complex: drive to work, if this road is blocked, take the other logistical road, while driving don't text, increase decrease and average speed variations, keep eyes on the road, etc....

On the Algorithms page of this blog, I will post every algorithm I do from FCC and other sources that comes up. You will see the questions, my thought process of analyzing such, and the finished code logic. I hope you enjoy reading this as much as I enjoyed coding it.

The latest algorithm I completed was the reverse an array algorithm. It is one of the first challenge on the algorithms sections of FCC's website.

Website: FCC.

Instructions: The instructions basically said to reverse this JavaScript string.

Thought process: Because the instructions are very simple, my thought process was very quick and structured. When dealing with JavaScript, we have to keep in mind that it is a loosely typed language, one of the results of this is that the variable data type, will dynamically change, based on the data that's entered. Keeping that in mind, we now know the reverseString() method first takes in a string, thus we can start by using "string" modification and parsing logic. This first code we need to write, line 4, is to split the string with the split() method. "The split() method splits a String object into an array of strings by separating the string into substrings." The reason I decided to do this is because the "str" variable will now become an array, and that's what we want because it is quite easy to reverse an array in JavaScript because all we need to do is call the reverse() method on the array. But to first do this we had make the "str" variable hold the array data. Now that that is accomplished, we can then use the .reverse()  method on the "str" variable *(line 5)* because it now holds array data. Now that I both split the string data into an array, and then reversed the array, it is now time to join the contents of the array back together which will then form back into a string. We do this by using the .join() method, which joins all elements of an array into a string. Now the only thing left is to return the parsed parameter. 

No comments:

Post a Comment