<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Danny Correia on Medium]]></title>
        <description><![CDATA[Stories by Danny Correia on Medium]]></description>
        <link>https://medium.com/@danfcorreia?source=rss-feee01d79649------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*liSPDkzPReRBsDcm.jpg</url>
            <title>Stories by Danny Correia on Medium</title>
            <link>https://medium.com/@danfcorreia?source=rss-feee01d79649------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 13:44:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@danfcorreia/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Max Product Algorithm (Ruby)]]></title>
            <link>https://medium.com/@danfcorreia/max-product-algorithm-ruby-4e1c184e5a21?source=rss-feee01d79649------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e1c184e5a21</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Danny Correia]]></dc:creator>
            <pubDate>Mon, 21 Oct 2019 00:57:10 GMT</pubDate>
            <atom:updated>2019-10-21T00:57:10.137Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*gDPt8NJ-fT3uUWJ77gTSmA.gif" /></figure><p>I’m use to solving algorithms at this point solely in JavaScript, but am forgetting how much easier the solve can be in a more powerful language like Ruby. The algorithm this time being quite simple: Given an array of numbers, return the highest product of 2 different numbers inside the array.</p><p>Let’s start off by examining the array:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*Uo1eDPE9qnbevBR7ZivpGA.png" /></figure><p>Looks simple enough, good practice would be to ask if the numbers can be multiplied with themselves. For this algorithm we’re going to say no, the number can’t be multiplied with itself. Questions like this will help us map out our code.</p><p>A good approach would be to store the highest product in a variable and then compare the value of that product to the current product. If the current product is at a higher value, we’ll replace the value stored in the variable with that current product. If not, we’ll do nothing and continue multiplying numbers through the array. Another approach we can do is to store all the products of the numbers into a new array and thanks to the Ruby enumerator #max we can pull the highest value. For the sake of Time Complexity we’re not going to use that approach as it is another loop and we want to have a clean solve.</p><p>Another powerful enumerator in ruby is the #each_with_index. It is exactly like the #each enumerator we’re use to only this one will assign an index number as it’s looping through the array. This will work out great as it will track where we are in the array as we loop.</p><p>Let’s give it a go:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*foP3NqtbL2WMh5EO9J_GKw.png" /></figure><p>Here unfortunately the loops are nested since we are comparing 2 different elements in the same array. This isn’t ideal, but it will make our logic a lot easier to code out. We’re going to set our variable up to store the highest product and use it to compare to other products as we loop through. We’ll se it to zero so we can make sure our first product will essentially always be stored and proceed from there. Since we’re tracking our progress with an index, to solve the issue of not multiplying the same number into each other we can simply craft a conditional comparing the indexes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*2lGdH27gc_zYSLPVEVamLQ.png" /></figure><p>If you take notice I used #next in the conditional, yet another powerful ruby method. Essentially #next tells the iteration in the code block to stop at the position it’s in, and calls on the parent loop to proceed onto the next set of numbers in the iteration of the array. Now that we’ve solved that edge case we can continue our logic. As explained before we’re simply going to take our current highest product that we stored in our variable, and compare it to the current product in our iteration. If that product is higher in value than the value stored in our variable, we’re going to store that new high value into the product. Once we’re done we’re going to simply return whatever value is in that product for our final answer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*U14ejRnYfhyc_tOuV-wn_A.png" /></figure><p>Another great thing about ruby is that it’s self returning, so we can simply just type out our variable’s name outside of the looping code block and it will return our answer.</p><p>This was a fun little exercise and hopefully will inspire you to try out different languages when practicing algorithms. Some solves that can be long in code might be shorter in a different language with built in methods.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e1c184e5a21" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting up a Database Class (MongoDB) for interactions in Python]]></title>
            <link>https://medium.com/analytics-vidhya/setting-up-a-database-class-mongodb-for-interactions-in-python-6a16417cd58e?source=rss-feee01d79649------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a16417cd58e</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Danny Correia]]></dc:creator>
            <pubDate>Mon, 14 Oct 2019 00:33:04 GMT</pubDate>
            <atom:updated>2019-10-20T14:33:52.555Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*8lYmtyFVLAsQ0VbWZRKnRw.gif" /></figure><p>Through my journey in python I’ve come across little tricks to streamline my code. One of them is creating a Database class to interact with my MongoDB.</p><p>Let’s start by creating a new file “database.py”. We’ll start off by creating our Database class:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*BlaqAaW73BGy9Tmji_dfVw.png" /></figure><p>This class gets passed “object” so our Database can inherit all the things an object can do inside python as well as the methods we create inside this class. The other 2 variables are static and are things we’re going to need to tell our class where to connect to for our Database. In this example it will be our MongoDB. URI (universal resource identifier) will basically be our mongodb address and for now we’re going to leave DATABASE as “none”.</p><p>This class is not the conventional class we’re use to making in OOP. We’re not initializing anything because we’re not going to be creating instances of different databases. With that being said, it’s safe to say we’re not going to be using “self” or instance methods.They’re all going to have the same static URI, we’re not going to have different URI’s. So with no instance methods we’re going to need to tell python the methods we’re going to be creating aren’t instance methods and we won’t be using self. We do that by adding “@staticmethod” before our method.</p><p>Let’s create a method called “initialize” that starts the connection to our database. We’re also going to need to import pymongo to accomplish this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wsFDoTjuJ-jA9fnpTboOfg.png" /></figure><p>Here you notice we’re using “Database.URI” instead of “URI”. This is because URI lives in the class Database and we need to tell python where to find it since we’re not using “self”. Same goes for “DataBase.DATABASE”. We’re using pymongo and feeding it the URI, then setting “DATABASE” to our desired database in our mongodb. From there we can work on one collection or many collections and reference it to any method in our class now.</p><p>Let’s start making some methods now to interact with out Database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S46HvoivWjpKMYPTl74-jQ.png" /></figure><p>Our insert method is going be how we add or “insert” data into our database. It’s going to take arguments of the desired “collection” to where we want to insert our information within the database and “data” being that information. So what if we want to retrieve information?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kc8hALETB1TXmasxy6QOtg.png" /></figure><p>Our #find and #find_one methods will do that for us. Just like the #insert method it needs to take in an argument of a collection so we know where exactly in our database to look, only this time instead of data it’s going to take a “query” or what it is we’re looking for.</p><p>Now in our app.py we’re going to have to run #Database.initialize() so it can start our connection and we can freely run these other methods. In doing so we will also have to import the Database class into the file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*tdVs589UKExhGSse7Dc8vw.png" /></figure><p>When we run our app this method will invoke, our Database class will initialize, and it will be ready for use! From here with these concepts we can continue to write more methods in other classes to further utilize this connection to our MongoDB.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a16417cd58e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/setting-up-a-database-class-mongodb-for-interactions-in-python-6a16417cd58e">Setting up a Database Class (MongoDB) for interactions in Python</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fibonacci (Iterative)]]></title>
            <link>https://medium.com/@danfcorreia/fibonacci-iterative-28b042a3eec?source=rss-feee01d79649------2</link>
            <guid isPermaLink="false">https://medium.com/p/28b042a3eec</guid>
            <category><![CDATA[fibonacci]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Danny Correia]]></dc:creator>
            <pubDate>Mon, 07 Oct 2019 01:49:19 GMT</pubDate>
            <atom:updated>2019-10-07T01:49:19.188Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the classic recursive algorithms you’ll see is for the Fibonacci Sequence. In this blog post I’ll be going over the iterative solve.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*Hja1pcjNv-7ZJAX0j9rfJQ.gif" /></figure><p>Fibonacci Sequence is a sequence of numbers where the value of the current number is the value of the previous 2 numbers added together. An example would be:</p><pre>0, 1, 1, 2, 3, 5, 8, 13, 21...</pre><p>In an algorithm question they’ll usually ask you something like “Given a Number, return the value of that index in the sequence”. So with the example above, if the given number was 8 then 21 would be returned.</p><p>Let’s setup our function with what we know:</p><pre>function fibonacci(number){</pre><pre>}</pre><p>We’re going to need to create our sequence, so looken back at the example before:</p><pre>0, 1, 1, 2, 3, 5, 8, 13, 21...</pre><p>We know that we need to start with the first two numbers to begin the sequence. Let’s add that into our function:</p><pre>function fibonacci(number){<br>     let sequence = [0,1]</pre><pre>}</pre><p>Also with this array setup, we know that we’re returning the index of that number in the sequence:</p><pre>function fibonacci(number){<br>     let sequence = [0,1]</pre><pre>     return sequence[number]</pre><pre>}</pre><p>Now we need to add our logic to create the sequence. Just like almost all of the other algorithms, we start off with a for loop only this time we’re going to set it up a little differently. Instead of setting “i” equal to “0”. We’re going to set it to “2”. This is because we already have our indexes 0 and 1 set in our sequence:</p><pre>let sequence = [0,1]</pre><p>We also are going to set the loop only to execute until we reach the given index of the sequence so we’re going to use the operator “≤”:</p><pre>function fibonacci(number){</pre><pre>     let sequence = [0, 1];</pre><pre>     for (let i = 2; i &lt;= number ; i++){</pre><pre>     }</pre><pre>     return sequence[number];</pre><pre>}</pre><p>Now we simply need to add to our values to the sequence. We know the pattern is the previous two numbers is the value of the next number of the sequence. So let’s insert that logic into our function:</p><pre>function fibonacci(number){</pre><pre>     let sequence = [0, 1];</pre><pre>     for (let i = 2; i &lt;= number ; i++){<br>        <br>          sequence.push(sequence[i - 2] + sequence[i -1])</pre><pre>     }</pre><pre>     return sequence[number];</pre><pre>}</pre><p>There we have it! This iterative approach seems simple enough, but the recursive one looks even simpler:</p><pre>function fibonacci(number) {</pre><pre>  if (number &lt; 2){</pre><pre>    return number;</pre><pre>  }</pre><pre>  return fibonacci(number - 1) + fibonacci(number - 2)</pre><pre>}</pre><p>Sometimes the cleanest looking code isn’t the best. In Big O terms our iterative solve will execute quicker with a notation of O(n) while the recursive solve is O(2^n). If we were to run the same functions with 50 as the given index we’d be able to see this in action. The result being our iterative approach executing much faster than our recursive.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28b042a3eec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a Model in Python (OOP)]]></title>
            <link>https://medium.datadriveninvestor.com/create-a-model-in-python-oop-b117015f08f2?source=rss-feee01d79649------2</link>
            <guid isPermaLink="false">https://medium.com/p/b117015f08f2</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[oop]]></category>
            <dc:creator><![CDATA[Danny Correia]]></dc:creator>
            <pubDate>Sat, 28 Sep 2019 16:24:44 GMT</pubDate>
            <atom:updated>2019-09-29T14:16:18.981Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*kNnDF3wkle0_JyNgQFvyNg.png" /></figure><p>All objects have some properties and a number of different things they can do. With that same thinking, all objects can be deconstructed into different properties and actions. Let’s take for an example a database of films. They are all going to have properties like Title, Rating, Run-time, etc. Wouldn’t it be easier to have a way to just classify all those properties into one class for all films? This is when OOP comes into play.</p><p>We can start by creating a “Film” model. In a new file we’ll define our class:</p><pre>class Film(object):<br></pre><p>We use “class” to classify Film. We pass it an object because it is an object and comes from an object, by doing this we can treat it as such.</p><p><a href="https://www.datadriveninvestor.com/2019/03/25/a-programmers-guide-to-creating-an-eclectic-bookshelf/">A Programmer&#39;s Guide to Creating an Eclectic Bookshelf | Data Driven Investor</a></p><p>Now we need to assign it attributes. Making sure that every time a new film is created, it’s giving the same attributes as every other film. We’ll create a function or action to do so:</p><pre>def __init__(self):</pre><p>Let’s take a look at this before continuing. The function “__init__” , short for initializing, will run every time a new Film object is created. The “self” is what’s being created, we’ll pass it in and then assign it properties. Let’s start assigning it 3 basic properties to start off with.</p><pre>def __init__(self):<br>        self.title = &quot;Men in Black&quot;<br>        self.rating = &quot;PG-13&quot;<br>        self.runtime = &quot;1h 55m&quot;</pre><p>This next step we’re assigning a Film it’s title, rating, and run-time. Looks like we’re all set, let’s see how this would work.</p><pre>film = Film()</pre><p>Here we are creating an instance of a “Film” by assigning it to “film”. Making “film” and instance of the class Film. This will now assign “film” all the properties and functionality of the class Film. If we&#39;re to do something like this now:</p><pre>film.title<br> #&quot;Men in Black&quot;</pre><p>Here “film.title” will now return “Men in Black”. Great! We seem to have a working class now. The only issue is that any instance of the film will have the same title because we statically assigned the title. What if we wanted a different title. We could simply do this:</p><pre>film = Film()</pre><pre>print(film.title)<br> #// &quot;Men in Black&quot;</pre><pre>film.title = &quot;Pretty Woman&quot;</pre><pre>print(film.title)<br># &quot;Pretty Woman&quot;</pre><p>We can change it that way but seems tedious to do this every time. So let’s go back to our Film model and set it up to be more dynamic.</p><pre>class Film(object):<br>    def __init__(self, title, rating, runtime):</pre><p>What if we set it up to also require to take in attributes so we can assign it’s properties to those specific attributes. Just like how we did it before, only we’ll assign the properties to those place holders:</p><pre>class Film(object):<br>    def __init__(self, title, rating, runtime):<br>        self.title = title<br>        self.rating = rating<br>        self.runtime = runtime</pre><p>Looks good! Let’s see what happens now:</p><pre>film = Film()</pre><pre>print(film.title)</pre><pre>//TypeError: __init__() takes exactly 4 arguments (1 given)</pre><p>We get an error, but it’s a good sign! It’s showing it’s working if we read it properly. It’s saying it’s missing arguments which is our “title, rating, runtime”. You might be confused as to why it’s saying 1 was given. That’s because it’s referring to the “self” which is the instance we’re creating. Let’s give it the rest of the attributes:</p><pre>film = Film(&quot;Pretty Woman&quot;, &quot;R&quot;, &quot;2h 5m&quot;)</pre><pre>print(film.title)<br># &quot;Pretty Woman&quot;</pre><p>It worked! The next step would be to seed it into our database, and that would all depend on what kind you’re using. If you’re using MongoDB you might have to create a function inside your Film model that transforms the data into JSON format before inserting.</p><p>This is the very basic creation and idea behind a model in OOP with python. Its uses help us speed up and maintain structure in our program. I hope you enjoy and have fun playing with this concept!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fb2a0d6%3Fas_embed%3Dtrue&amp;dntp=1&amp;display_name=Upscribe&amp;url=https%3A%2F%2Fupscri.be%2Fb2a0d6%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/0707f5c806284d01a4a13c7b13a91ce3/href">https://medium.com/media/0707f5c806284d01a4a13c7b13a91ce3/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b117015f08f2" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/create-a-model-in-python-oop-b117015f08f2">Create a Model in Python (OOP)</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Insertion Sort]]></title>
            <link>https://medium.com/@danfcorreia/insertion-sort-20aeb425f44d?source=rss-feee01d79649------2</link>
            <guid isPermaLink="false">https://medium.com/p/20aeb425f44d</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[sorting-algorithms]]></category>
            <dc:creator><![CDATA[Danny Correia]]></dc:creator>
            <pubDate>Mon, 23 Sep 2019 02:38:45 GMT</pubDate>
            <atom:updated>2019-09-23T17:57:11.835Z</atom:updated>
            <content:encoded><![CDATA[<p>Insertion Sort is an interesting algorithm compared to the others I’ve written about, Mostly because it’s the closest on how we would go about sorting in the real world. With that being said, it doesn’t mean it’s the most efficient, but given the right circumstance ( like an already slightly sorted array or small data structure) it can be our best option in terms of Big O. In the best of cases leaving us with a Big O of O(n).</p><p>So! How does it work?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*qc-KD7DII1K097jnvOWqsg.gif" /></figure><p>Essentially we’re taking the number and finding what two elements we can put that number between. Let’s take an array of numbers:</p><pre>let array = [4,2,6,1,9,8,7]</pre><p>Let’s start with the first element 4. We’ll compare 4 with the next element 2. In this case 2 is less than 4 so we’ll move 2 to the beginning of the array:</p><pre>let array = [2, 4, 6, 1, 9, 8, 7]<br></pre><p>Now let’s look at 6 and see where we can fit this one in our previous elements of the array. 6 is larger than 4 so we can keep 6 at the end of our list for now. This will move us onto our next element 1. What value does 1 have compared to our previous elements in the array? It’s the smallest number so we can add it to the beginning of the array:</p><pre>let array = [1, 2, 4, 6, 9, 8, 7]</pre><p>Next up is 9, 9 is larger than 6 so we can leave 9 where it is and continue onto the following element. Our following element is 8, let’s find out where it stands compared to our previous elements. 8 is less than 9 but larger than 6 so we can place it in between, leaving us with 7. With the same logic we know 7 is less than 9 and 8 but larger than 6. We can safely say 7 will go between the elements 6 and 8.</p><pre>let array = [1, 2, 4, 6, 7, 8, 9]</pre><p>How do we code this? Now here comes the fun part, First we start with our For Loop. Now that we’re looping through the array we want to create some logic to check and see if our current number is less than the first number in the array, and if it is, to place it at the first index and moving everything element over one index:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*V3VfXAT9WSGYo2lAJZ60kQ.png" /></figure><p>Great! Now let’s create some logic that deals if the number in the index before it is smaller. If it’s true we need to find a spot for it making us loop through the numbers in the indexes before it (the ones we already sorted through).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OrhW6EFq36AC2Ta-AJ64TA.png" /></figure><p>As you can see we’re setting the conditional in the loop to start at 1 (we already made our comparison to the first element in the array) and loop through until it reaches the element we’re currently on.</p><p>Our final conditional will be to find between which numbers our current one will fit between.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*nTAFPy_8fWyklY9pFMxBWQ.png" /></figure><p>This Boolean stating that if the current element is greater than or equal to the element on the left and less than the current element we’re on, let’s implement some logic to place the number here!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*F57iPsAGKjNtIGsmo2cJNw.png" /></figure><p>Looks a bit messy and not ideal but like stated earlier, given the right problem this can be the best solution. If we run the code it’ll give us our desired output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*iM5-WDLy7rti1FCCI_6SNg.png" /></figure><p>I believe there’s one more sort I have yet to touch upon and it’s Merge Sort. Keep an eye out for it!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20aeb425f44d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Selection Sort in JavaScript]]></title>
            <link>https://medium.com/@danfcorreia/selection-sort-in-javascript-c7fbb60364a0?source=rss-feee01d79649------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7fbb60364a0</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[sorting-algorithms]]></category>
            <dc:creator><![CDATA[Danny Correia]]></dc:creator>
            <pubDate>Mon, 16 Sep 2019 02:43:41 GMT</pubDate>
            <atom:updated>2019-09-16T02:43:41.525Z</atom:updated>
            <content:encoded><![CDATA[<p>Selection Sort is another simpler way of sorting an array in JavaScript. Much like the Bubble Sort, Selection Sort is also a Time Complexity issue as it’s O(n²). It takes nested loops but does things a little differently.</p><p>Like Bubble Sort, we’re after the lowest number in the array. Instead of checking the number next to it and swapping positions, we’re going to do things a little differently. We’re going to take the lowest number and scan the rest of the numbers in an array until we find one lower. If we don’t, we’ll place our lowest number in the beginning of the array and start at the second element of the array. If we do find a lower number, we’ll take our focus onto the new number and scan the rest of the array for an even lower number.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*H2bCd6eoIONJIUnG5Jm9sQ.gif" /></figure><p>Let’s see this an action! We’ll start with an array:</p><pre>const array= [100, 56, 8, 4, 3, 1, 64, 63, 205, 0] </pre><p>Next let’s declare our function and start our first For Loop:</p><pre>function sort(arr) {</pre><pre>    for(let i = 0; i &lt; arr.length; i++){</pre><pre>    }<br>}</pre><p>Now we know we need to start from our first element so let’s store information in two different variables. We’ll store our current lowest index in the array into the “lowest” variable and the value of that index into a variable called “temp”.</p><pre>function sort(arr) {</pre><pre>    for(let i = 0; i &lt; arr.length; i++){</pre><pre>      let lowest = i;<br>      let temp = arr[i];<br>    }<br>}</pre><p>We’ll start our scan with our second For Loop.. Keeping in mind we’ll have to start from the index next to our current, so “j” will have to equal i+1:</p><pre>function sort(arr) {</pre><pre>    for(let i = 0; i &lt; arr.length; i++){<br>      let lowest = i;<br>      let temp = arr[i];</pre><pre>      for(let j = i+1; j &lt; arr.length; j++){</pre><pre>      }<br>    }<br>}<br></pre><p>Great! All we need now is to implement some logic in a conditional. What if the index contains a number of lower value? We’ll have to update our “lowest” variable:</p><pre>function sort(arr) {</pre><pre>    for(let i = 0; i &lt; arr.length; i++){<br>       let lowest = i;<br>       let temp = arr[i];</pre><pre>       for(let j = i+1; j &lt; arr.length; j++){</pre><pre>          if (arr[j] &lt; arr[lowest]){<br>             lowest = j;</pre><pre>          } </pre><pre>       }<br>    }<br>}</pre><p>This is looking pretty good but as far as actually moving the elements around accordingly, we’re missing that last piece of logic. This is when our variables come in handy! We’ll use them to implement the last piece of logic…swapping out the elements:</p><pre>const array= [100, 56, 8, 4, 3, 1, 64, 63, 205, 0]</pre><pre>function sort(arr) {</pre><pre>    for(let i = 0; i &lt; arr.length; i++){<br>       let lowest = i;<br>       let temp = arr[i];</pre><pre>       for(let j = i+1; j &lt; arr.length; j++){</pre><pre>           if (arr[j] &lt; arr[lowest]){<br>              lowest = j;</pre><pre>           }</pre><pre>       }</pre><pre>       arr[i] = array[lowest];</pre><pre>       arr[lowest] = temp;</pre><pre>   }</pre><pre>   return arr;</pre><pre>}</pre><p>There you have it! Our Selection Sort. Another simple sort but not the most productive time wise. You can imagine how this might be time consuming if we gave it an array of lets say 100 numbers? It’s another tool in your toolbox, it’s up to you on how to use it!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7fbb60364a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bubble Sort In JavaScript]]></title>
            <link>https://medium.datadriveninvestor.com/bubble-sort-in-javascript-298375020b29?source=rss-feee01d79649------2</link>
            <guid isPermaLink="false">https://medium.com/p/298375020b29</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[sorting]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Danny Correia]]></dc:creator>
            <pubDate>Sat, 07 Sep 2019 21:08:45 GMT</pubDate>
            <atom:updated>2019-09-25T09:15:46.266Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*0aPxBKrbMTVbF0UCI6gxZg.gif" /></figure><p>There are a few different sorting methods you can use when solving Algorithms, each sort with their own strengths and weaknesses. Depending on what&#39;s called for, it’s up to you to decide which would be the best fit for the solution. Today I’m going to be talking about one of them, Bubble Sort.</p><p>The GIF at the top of the page does pretty well with the visual aspect. Let’s say given an array of numbers, put the numbers in order from least to greatest.</p><p><a href="https://www.datadriveninvestor.com/2019/03/22/the-seductive-business-logic-of-algorithms/">The Seductive Business Logic of Algorithms | Data Driven Investor</a></p><pre>array = [4,2,5,6,1,3]</pre><p>The idea behind bubble sort is you’re going to take the first number in the array 4 and compare it to the next number in the array 2. We know 4 is larger than 2 so we’ll switch it:</p><pre>array = [2,4,5,6,1,3]</pre><p>Now we repeat the same logic. We take 4 and compare it to the next number 5. This time 5 is the larger number so 4, for now, stays in its position. Now we take 5 and compare it to it’s neighboring number 6. 6 is larger than 5 so 5 stays in it’s position and now we’re working with 6. We compare 6 to the next number which is 1. 6 is greater than 1 so we switch their positions.</p><pre>array = [2,4,5,1,6,3]</pre><p>As you can guess next will be the comparison of 6 and 3, 6 being the larger number will take 3’s place:</p><pre>array = [2,4,5,1,3,6]</pre><p>Now we loop again! Starting the same process from the beginning. 2 and 4, 2 stays and now we work with the larger number 4. We’re “bubbling” up the larger number in our loop and eventually will be left with the array in order.</p><p>This in terms of big O as you can see would be insanely slow given an array of 100 numbers, or even 500 numbers. As far as time complexity goes, Bubble sort is not the ideal option. Now that we understand the idea of bubble sort, let’s turn it into code.</p><p>Let’s take that same array and write a function called “bubble”.</p><pre>const array = [4,2,5,6,1,3]</pre><pre>function bubble(arr){</pre><pre>}</pre><p>We know we’re looping and comparing elements in the array so that right from the start is going to hint that we’ll need a nest loop. So let’s set those up:</p><pre>const array = [4,2,5,6,1,3]</pre><pre>function bubble(arr){<br>    for(let i = 0; i &lt; arr.length; i++){<br>        for(let j = 0; j &lt;arr.length; j++){</pre><pre><br>        }</pre><pre>    }</pre><pre>}</pre><p>Now that we have our for loops set up let’s start the logic for the comparison. We’ll do this by creating a conditional comparing one element to the next and in that logic, if the first element is larger than the second, we’ll switch their places.</p><pre>const array = [4,2,5,6,1,3]</pre><pre>function bubble(arr){<br>    for(let i = 0; i &lt; arr.length; i++){<br>        for(let j = 0; j &lt;arr.length; j++){<br>           if(array[j] &gt; array[j+1]){<br>               let temp = arr[j]<br>               arr[j] = array[j+1]<br>               arr[j+1] = temp</pre><pre>           <br>           }</pre><pre>        }</pre><pre>    }</pre><pre>}</pre><p>This logic might seem a little confusing to follow so let’s go a little more in-depth.</p><pre>// here we&#39;re saying if the first element is larger than the second, //let&#39;s execute some code to swap their positions</pre><pre>if(array[j] &gt; array[j+1]){</pre><pre>//in this line we&#39;re storing the value of the first element into a //temporary variable </pre><pre>            let temp = arr[j]</pre><pre>// Now in this line we&#39;re simply moving our first element(the larger // number)in the position of the following element (the smaller<br>// number)</pre><pre>            arr[j] = array[j+1]</pre><pre>// and our missing piece is setting the second element (the smaller number into the previous element&#39;s position in the array. We stored this value in the variable &quot;temp&quot; for this reason, as the value is now different because of our previous line.</pre><pre>               arr[j+1] = temp</pre><p>Once this finishes executing and bubbles our largest number to the end of the array. It will execute the outer Loop to repeat the process until our array is sorted.</p><p>So what do we know? Bubble sort for Time Complexity does not seem efficient due to the reasoning of needing nested loops, giving us a big O of O(n²). The Pro though is that is doesn’t create a new data structure so as far as Space Complexity it’s favorable.</p><p>I hope this clarifies exactly what a Bubble sort is and how it’s used. It isn’t the most popular sort for algorithms but every sort has its use. Knowing them all will help you make better choices when solving future algorithms.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fb2a0d6%3Fas_embed%3Dtrue&amp;dntp=1&amp;display_name=Upscribe&amp;url=https%3A%2F%2Fupscri.be%2Fb2a0d6%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/0707f5c806284d01a4a13c7b13a91ce3/href">https://medium.com/media/0707f5c806284d01a4a13c7b13a91ce3/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=298375020b29" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/bubble-sort-in-javascript-298375020b29">Bubble Sort In JavaScript</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Two Sum Algorithm]]></title>
            <link>https://medium.com/@danfcorreia/two-sum-algorithm-7f4a2c40c9f1?source=rss-feee01d79649------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f4a2c40c9f1</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Danny Correia]]></dc:creator>
            <pubDate>Sun, 01 Sep 2019 00:54:20 GMT</pubDate>
            <atom:updated>2019-09-01T00:54:20.465Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*qvrmKkhAryh0byp4glsmhQ.gif" /></figure><p>One of the many popular algorithms is the Two Sum Algorithm. Given an array of numbers and a stand alone number, return all combinations of numbers in the array that add up to the stand alone number. Although any approach that works is technically a solve, but Big O determines which is the best answer for your application. Today we’ll shoot for time complexity!</p><p>Let’s start for example with the following:</p><pre>let array = [2,5,8,3,-2,9,0]<br>let targetSum = 3</pre><p>So the array of numbers we’re working with is 2,5,8,3,-2,9,0. We need to find the number combinations that we’ll equal 3, our “targetSum”.</p><p>Let’s code with brute force to get our solution. What do we know we need to do? We need to take the first number and add it against every other number in the array to check if it equals our target sum. If it does, we’ll take note and continue down the line. For this we’re going to use our good old friend “For loop”!</p><p>Let’s start out by creating a variable where we’ll store our combinations that meet our criteria.</p><pre>const findTwoSum = (arr,sum)=&gt;{<br> <br> let results = []</pre><pre>}</pre><p>We’ll call it “results” and have it be an array since we might have more than one combination. Now let’s start our loop:</p><pre>const findTwoSum = (arr,sum)=&gt;{<br> <br>  results = []<br>  <br>  for(let i = 0; i &lt; arr.length; i++){</pre><pre>}</pre><p>That will get us our first number in the array but now we need to loop through the other numbers in the array. We’ll have to create ANOTHER loop and nest it our first one. We can’t use our variable “i” since we used in our first loop. So let’s use “j” for our nested second loop.</p><pre>const findTwoSum = (arr,sum)=&gt;{<br> <br>  results = []<br>  <br>  for(let i = 0; i &lt; arr.length; i++){<br>    <br>    for(let j = 0; j &lt; arr.length; j++){<br>      <br>  <br>      <br>    }<br>    <br>  }<br>  <br>}</pre><p>Awesome! It looks like our loops are all lined up, now let’s start our logic. we need to add our looped elements together and see if it equals our target sum.</p><pre>arr[i] + arr[j] === sum</pre><p>Let’s make this a conditional that if this statement is true, we’ll add this combination of elements to our “results” area we declared earlier.</p><pre>let array = [2,5,8,3,-2,9,0]<br>let targetSum = 3</pre><pre>const findTwoSum = (arr,sum)=&gt;{<br> <br>  results = []<br>  <br>  for(let i = 0; i &lt; arr.length; i++){<br>    <br>    for(let j = 0; j &lt; arr.length; j++){<br>      <br>      if (arr[i] + arr[j] === sum){<br>        results.push([arr[i], arr[j]])<br>       <br>      }<br>      <br>    }<br>    <br>    <br>  }<br>  <br>  return results<br>}</pre><p>We’ll use our .push() method and return “results” at the end of our function. Our output should result in:</p><pre>[[5, -2], [3, 0], [-2, 5], [0, 3]]</pre><p>Although this gives us our solutions, the bigger the array input the slower this will run. O(n²) isn’t an ideal solution so let’s do it better.</p><p>I think we could do a O(n) solution here by revisiting Hashmaps!</p><pre>const findTwoSum = (arr, sum) =&gt;{<br>  let results = []<br>  let map = {}</pre><pre>}</pre><p>We’ll be doing almost the same logic, only this time we’ll be creating a hashmap instead of a nested loop.</p><pre>const findTwoSum = (arr, sum) =&gt;{<br>  let results = []<br>  let map = {}<br>  <br>  for(let i = 0; i &lt; arr.length; i++){<br>    <br>  }<br>}</pre><p>Just like before we’re starting with a For Loop, but this time our logic will be a little different. Let’s take our targeted sum and subtract it from a number in the array, then take the result (which would be the different of the target sum and the element) and see if that remainder exists in the array. Sounds like another nested loop? Not Quite. If we can create a hashmap and just see if the remainder exists in the hash it will take place of what would’ve been a nested loop. We’ll set the number in the array as the key, and have “true” be the value.</p><pre>const findTwoSum = (arr, sum) =&gt;{<br>  let results = []<br>  let map = {}<br>  <br>  for(let i = 0; i &lt; arr.length; i++){<br>    map[arr[i]]=true<br>    let diffOfElementAndSum = sum - arr[i]</pre><pre>  }<br>  <br> <br>  <br>}</pre><p>To complete this logic we’ll need to store the difference between the 2 numbers in a variable. I know “diffOfElementAndSum” is a little wordy but will make this less confusing. This is starting to already look a little more readable then our previous solve. Now all we have to do is take “diffOfElementAndSum” and see if it exists in our hash “map”.</p><pre>if(map[diffOfElementAndSum]){<br>      results.push([arr[i], diffOfElementAndSum])<br>}</pre><p>In this logic we’re inserting the value of “diffOfElementAndSum” into our “map” hash to see if it exists as a key. If it returns “true” we’re going to take that element and the value of “diffOfElementAndSum” and add it to our “results” array as a combination that reaches out target sum. If not, we’ll keep executing the code. Let’s see it all together:</p><pre>const findTwoSum = (arr, sum) =&gt;{<br>  let results = []<br>  let map = {}<br>  <br>  for(let i = 0; i &lt; arr.length; i++){<br>    map[arr[i]]=true<br>    let diffOfElementAndSum = sum - arr[i]<br>     <br>    <br>    if(map[diffOfElementAndSum]){<br>      results.push([arr[i], diffOfElementAndSum])<br>    }</pre><pre>  }<br>  <br>  return results<br>  <br>}</pre><p>Our output on this should result in:</p><pre>[[-2, 5], [0, 3]]</pre><p>Our answer is the same and little cleaner. This solve is ideally more scalable for the fact it will run faster no matter the size of the input array. I’m sure there might be an even better solve so feel free to try it out for yourself! What about 3 sum? 4 sum? What logic would you use to solve those? Let the fun begin!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f4a2c40c9f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Redux Refresher]]></title>
            <link>https://medium.com/@danfcorreia/redux-refresher-2ea016fd44d5?source=rss-feee01d79649------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ea016fd44d5</guid>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Danny Correia]]></dc:creator>
            <pubDate>Mon, 26 Aug 2019 01:54:41 GMT</pubDate>
            <atom:updated>2019-08-26T01:54:41.178Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’re not using Redux a lot chances are you probably forgot how to set it up. These blog is just a quick refresher on how to setup your redux in your react app. I’m not going to dive in too much, this is geared towards people who are already know redux, but forgot how to set it all up. It’s ok to admit!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*H2MMV-tACChYSLhRVMd7og.gif" /></figure><p>So let’s start from the beginning. Just like other libraries, we have to install. In the route path in your command line enter:</p><pre>npm install react-redux</pre><p>There, we’re done!</p><p>Just kidding, but it’s almost that easy….almost. Now we’re going to go into the Index.js file in your react app. We’re going to need to import a few things into your app. At the top with your other imports we’re going to add the components/files we’ll be using:</p><pre>import { createStore } from &#39;redux&#39;<br>import { Provider } from &#39;redux&#39;<br>import reducer from &#39;./reducer&#39;</pre><p>If you’ve noticed something different about the last import and how it’s not from redux, we’ll get to that in just a minute. Let’s use our first two imports and I’ll explain the thirds.</p><p>The createStore is something we’re going to use to, you guessed it, Create our store! We’ll also be taking the imported “reducer” file and passing it in as an argument.</p><pre>const store = createStore(reducer)</pre><p>Now that leaves us with the “Provider” component. This we’re going to wrap our App in and because it’s a component, we can give it properties. In this case we’re going to pass down the property “store”</p><pre>&lt;Provider store={store}&gt;<br>&lt;App/&gt;<br>&lt;/Provider&gt;</pre><p>You’re index page should look similar to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CuSsNKh10QgMvW3QWqYcyw.png" /></figure><p>Now, let’s talk about this reducer file. It’s where we’ll be storing our state and our handling of it! Just simply create the file for it in your app and make sure the path in the import is correct.</p><p>Let’s setup our state first:</p><pre>const defaultState={<br>name: value,<br>name:value<br>}</pre><p>For the sake of clarity, I’ll be using a previous project of mine for reference to an example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*FgY4il2KITxTK5DRdiYqEQ.png" /></figure><p>Next on the list we’ll setup our switch case where we’ll be handling our state. The very basic setup will be just as follows:</p><pre>function reducer(state=defaultState, action){<br>     switch(action.type){<br>          default:<br>            return state<br>     }<br>}</pre><p>As you can see reducer takes two arguments, state and action. At this point if nothing matches our action.type we’ll at least be returning state which we’ve set to always be our defaultState. The very last step is of course exporting the file at the very bottom:</p><pre>export default reducer</pre><p>To keep things cleaner, when things get a little too messy in the switch case, we can create functions outside of the reducer and call them inside of the switch case. As an example here’s what my reducer looked like on an earlier project:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_VrEvE74-4pnRU1PtefZHg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xzdPEpchlbGLlOsDuvP5Cg.png" /></figure><p>Now insert this import at the top of any component we want to use redux:</p><pre>import { connect } from &#39;react-redux&#39;</pre><p>We’ll take the connect and wrap the component in it at the bottom where we export giving it our two best friends as arguments (mapStateToProps, mapDispatchToProps).</p><pre>export default connect(mapStateToProps, mapDispatchToProps)(App)</pre><p>Now we can pass in mapStateToProps and mapDispatchToProps in as, you guessed it, properties! We can officially start using our redux in our react app:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2RU_fUptneQEFhFza05vnA.png" /></figure><p>I hope this helped. My intention wasn’t to teach Redux but rather have this as a refresher incase your remember how to use it, but forgot how to set it all up!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ea016fd44d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Reverse a String in JavaScript]]></title>
            <link>https://medium.com/@danfcorreia/how-to-reverse-a-string-in-javascript-8bdf92e8aaca?source=rss-feee01d79649------2</link>
            <guid isPermaLink="false">https://medium.com/p/8bdf92e8aaca</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Danny Correia]]></dc:creator>
            <pubDate>Sun, 18 Aug 2019 23:08:11 GMT</pubDate>
            <atom:updated>2019-08-18T23:29:41.855Z</atom:updated>
            <content:encoded><![CDATA[<p>This weeks blog will be short and simple. As I am still studying Algorithms you can still see a trend in my weekly blogs! Now as for the title this week I know what you’re thinking, .reverse() would do the trick. Well this week I’m going to show you yes the .reverse() way but also using decrementing loops! This will help you in your journey through the land of algorithms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*62zqyL320owqimznAn5nFg.gif" /></figure><p>Let’s start with the built-in functions JavaScript already comes with. We’ll be using the .split(), .reverse(), and .join(). First let’s get ourselves set up:</p><pre>let sentence = &quot;Try and Reverse this sentence!&quot;</pre><p>For making our code easier to read and show the extent of our function, let’s make the string we’re trying to reverse a sentence and store it in a variable.</p><pre>let sentence = &quot;Try and Reverse this sentence!&quot;</pre><pre>function reverse(string){</pre><pre>   string.split(&quot;&quot;)<br>}<br>reverse(sentence)</pre><p>.split() will take our string and break it up into an array of smaller strings. To see this we’ll console.log and see what it gives us:</p><pre>[ &#39;T&#39;,&#39;r&#39;,&#39;y&#39;,&#39; &#39;,&#39;a&#39;,&#39;n&#39;,&#39;d&#39;,&#39; &#39;,&#39;R&#39;,&#39;e&#39;,&#39;v&#39;,&#39;e&#39;,&#39;r&#39;,&#39;s&#39;,&#39;e&#39;,&#39;     &#39;,&#39;t&#39;,&#39;h&#39;,&#39;i&#39;,&#39;s&#39;,&#39; &#39;,&#39;s&#39;,&#39;e&#39;,&#39;n&#39;,&#39;t&#39;,&#39;e&#39;,&#39;n&#39;,&#39;c&#39;,&#39;e&#39;,&#39;!&#39; ]</pre><p>Pretty cool right? Great! Now we are working with an array. We can implement the .reverse() now and reverse all the elements in the array:</p><pre>let sentence = &quot;Try and Reverse this sentence!&quot;</pre><pre>function reverse(string){</pre><pre>string.split(&quot;&quot;).reverse()<br>}<br>reverse(sentence)</pre><p>Now this should theoretically reverse all our elements in the array. Let’s console.log it and check it out:</p><pre>[ &#39;!&#39;,&#39;e&#39;,&#39;c&#39;,&#39;n&#39;,&#39;e&#39;,&#39;t&#39;,&#39;n&#39;,&#39;e&#39;,&#39;s&#39;,&#39; &#39;,&#39;s&#39;,&#39;i&#39;,&#39;h&#39;,&#39;t&#39;,&#39; &#39;,&#39;e&#39;,&#39;s&#39;,&#39;r&#39;,&#39;e&#39;,&#39;v&#39;,&#39;e&#39;,&#39;R&#39;,&#39; &#39;,&#39;d&#39;,&#39;n&#39;,&#39;a&#39;,&#39; &#39;,&#39;y&#39;,&#39;r&#39;,&#39;T&#39; ]</pre><p>Alright! looks like we’re making some progress! Now for the last ingredient in out chain… the .join():</p><pre>let sentence = &quot;Try and Reverse this sentence!&quot;</pre><pre>function reverse(string){</pre><pre> return string.split(&quot;&quot;).reverse().join(&quot;&quot;)<br>}</pre><pre>reverse(sentence)</pre><p>After running this code you should get back ‘!ecnetnes siht esreveR dna yrT’.</p><p>Now if this was an algorithm question we’d probably wouldn’t get away with something as simple as that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*rOEOW1Vg-TQsL4-Rx2W_Yw.gif" /></figure><p>We’d probably want to go about this with our trusty friend the for loop! We’re use to the incrementing for loop but since we’re reversing, we’ll have to decrement. Let’s get started:</p><pre>let sentence = &quot;Try and Reverse this sentence!&quot;</pre><pre>function reverse(string){<br>let result = &quot;&quot;</pre><pre>}</pre><pre>reverse(sentence)</pre><p>For now let’s set up a variable to an empty string. The idea behind this is that as we loop we’ll feed the variable one letter at a time. Thats the beauty of strings in JavaScript, we could almost treat them like arrays. They even have their own indexes! We can write something as simple as sentence[2] and we’ll get back “y”. So having to use .split() kind’ve seems pointless here. Let’s start writing our for loop:</p><pre>let sentence = &quot;Try and Reverse this sentence!&quot;</pre><pre>function reverse(string){<br>let result = &quot;&quot;<br>  for(let i = string.length - 1; i &gt;= 0; i--){</pre><pre>  }<br>}</pre><pre>reverse(sentence)</pre><p>Before we go any farther let’s review how we setup our decrementing for loop. Just like any other for loop syntax we have to set the value of “i”. Only this time we’re starting at the end of the string, and because we can treat a string almost like an array we can start it at the last index. Like an array, we know the first index is ‘0’ not ‘1’ so we have to subtract ‘1’ from the length of the given string. Decrementing, you guessed it, is the opposite of incrementing so we’re going be looping until we’ve reached ‘0’. Which in this case will be the first index of the string. Let’s throw a console.log and see if it’s working:</p><pre>let sentence = &quot;Try and Reverse this sentence!&quot;</pre><pre>function reverse(string){<br>let result = &quot;&quot;<br>  for(let i = string.length - 1; i &gt;= 0; i--){<br>     console.log(string[i])</pre><pre>  }<br>}</pre><pre>reverse(sentence)</pre><p>That should return:</p><pre>y<br>!<br>e<br>c<br>n<br>e<br>t<br>n<br>e<br>s<br> <br>s<br>i<br>h<br>t<br> <br>e<br>s<br>r<br>e<br>v<br>e<br>R<br> <br>d<br>n<br>a<br> <br>y<br>r<br>T<br>&gt;</pre><p>Don’t worry about the appearance, remember it’s looping and giving us one letter at a time. It looks like it’s doing the trick! We need to find a home for all these substrings, which is why we created the variable “result”. We can use the “+=”(addition assignment operator) since we’re dealing with a string and add each substring value to our variable one at a time.</p><pre>let sentence = &quot;Try and Reverse this sentence!&quot;</pre><pre>function reverse(string){<br>let result = &quot;&quot;<br>  for(let i = string.length - 1; i &gt;= 0; i--){<br>     result += string[i]<br>     console.log(result)</pre><pre>  }<br>}</pre><pre>reverse(sentence)</pre><p>I threw in a console.log so we can see this happen as we loop through.</p><pre>!<br>!e<br>!ec<br>!ecn<br>!ecne<br>!ecnet<br>!ecnetn<br>!ecnetne<br>!ecnetnes<br>!ecnetnes <br>!ecnetnes s<br>!ecnetnes si<br>!ecnetnes sih<br>!ecnetnes siht<br>!ecnetnes siht <br>!ecnetnes siht e<br>!ecnetnes siht es<br>!ecnetnes siht esr<br>!ecnetnes siht esre<br>!ecnetnes siht esrev<br>!ecnetnes siht esreve<br>!ecnetnes siht esreveR<br>!ecnetnes siht esreveR <br>!ecnetnes siht esreveR d<br>!ecnetnes siht esreveR dn<br>!ecnetnes siht esreveR dna<br>!ecnetnes siht esreveR dna <br>!ecnetnes siht esreveR dna y<br>!ecnetnes siht esreveR dna yr<br>!ecnetnes siht esreveR dna yrT</pre><p>Look at it go! We can see that by the end of the loop it successfully added the entire string to the result variable. All we have to do now is return “result” at the end of our function:</p><pre>let sentence = &quot;Try and Reverse this sentence!&quot;</pre><pre>function reverse(string){<br>let result = &quot;&quot;<br>  for(let i = string.length - 1; i &gt;= 0; i--){<br>     result += string[i]<br>  }<br>  return result </pre><pre>}</pre><pre>reverse(sentence)</pre><p>With an end result of:</p><pre>=&gt; &#39;!ecnetnes siht esreveR dna yrT&#39;</pre><p>We did it! We didn’t have to chain up different built in functions! Understanding work arounds like this will help you as you continue doing algorithms. Maybe your next question will ask you to only reverse the words in a sentence longer than 3 letters? Now that you know how to use loops a little better you can try that on your own.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/244/1*UrtnhkQezlMK0cyISve-Sw.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8bdf92e8aaca" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>