<?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 Hybesis - H.urna on Medium]]></title>
        <description><![CDATA[Stories by Hybesis - H.urna on Medium]]></description>
        <link>https://medium.com/@urna.hybesis?source=rss-131ab5a2007------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*peuuKaIvFb4ABOU16G56qA.jpeg</url>
            <title>Stories by Hybesis - H.urna on Medium</title>
            <link>https://medium.com/@urna.hybesis?source=rss-131ab5a2007------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 15 Nov 2026 23:52:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@urna.hybesis/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[Handling Graphs With Adjacency Lists]]></title>
            <link>https://medium.com/swlh/handling-graphs-with-adjacency-lists-7e1befa93285?source=rss-131ab5a2007------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e1befa93285</guid>
            <category><![CDATA[traversals]]></category>
            <category><![CDATA[fb]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[adjacency-list]]></category>
            <category><![CDATA[graph]]></category>
            <dc:creator><![CDATA[Hybesis - H.urna]]></dc:creator>
            <pubDate>Mon, 27 Jul 2020 17:17:49 GMT</pubDate>
            <atom:updated>2020-08-01T23:37:34.018Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p><strong>An adjacency list represents a graph (or a tree)</strong> as an array of nodes that include their list of connections. Let’s first see how it looks like with a graph and its equivalent adjacency list representation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*L2SixXMf7thP0Osj.png" /></figure><p>The idea is pretty simple : the index of the array represents a node and each element in its list represents an outgoing connection with another node. Easy to create, easy to manipulate, here is how the data could be represented in JSON :</p><pre>[<br>  [1, 2, 3],<br>  [0, 2],<br>  [0, 1],<br>  [0]<br>]</pre><p><strong>Yes, it’s that simple!</strong> It includes all the information we need to go through and to visualize graphs or trees. This is for instance the data structure we choose to handle our mazes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/0*LHZc-WBmLpAzxpWC.png" /></figure><h3>Applications</h3><p>The advantage of the adjacency list implementation is that it allows us to <strong>compactly represent a sparse graph</strong>. The adjacency list also allows us to easily find all the links that are directly connected to a particular node. It is used in places like: <a href="https://hurna.io/en/academy/algorithms/maze_pathfinder/bfs.html">BFS</a>, <a href="https://hurna.io/en/academy/algorithms/maze_pathfinder/dfs.html">DFS</a>, <a href="https://hurna.io/en/academy/algorithms/maze_pathfinder/dijkstra.html">Dijkstra</a>, <a href="https://hurna.io/en/academy/algorithms/maze_pathfinder/a_star.html">A* (A-Star)</a> etc.</p><blockquote>Note: <strong>dense graphs</strong> are those which have a <strong>large number of edges</strong> and <strong>sparse graphs</strong> are those which have a <strong>small number of edges</strong>.</blockquote><blockquote>For a sparse graph with millions of vertices and edges, this can mean a lot of saved space.</blockquote><blockquote>Perfect, we know everything to create and manipulate our graphs!</blockquote><h3>Objectives</h3><blockquote>Operate Adjacency Lists and Graphs.<br>Build our own structures.<br>Understand graph traversal algorithms.<br>Understand the advantages over an adjacency matrix.</blockquote><h3>What is next?</h3><p>If you haven’t jumped yet to <a href="https://hurna.io/en/academy/algorithms/maze_generator/index.html">maze generation algorithms</a>, playing with them and using our <a href="https://hurna.io/en/academy/algorithms/explorers/maze_generator/binary.html">explorer</a> gives you visual insights of adjacency lists. We will soon study more graph data structures such as adjacency matrix which may be useful in particular cases.</p><h3>Build our own</h3><p>To model this in C++, we can <strong>create a class called Node</strong>, which has two member variables:</p><p>- <strong>data</strong>: Any extra data you want to store<br>- <strong>neighbors</strong>: List of outgoing connections (using index as id)</p><pre>struct Node<br>  {<br>    Node(const T&amp; data, set&lt; int &gt; connections) : <br>      data(data), neighbors(connections) {}</pre><pre>    T data;                // Any extra data you want to store<br>    set&lt; int &gt; neighbors;  // List of outgoing connections<br>  };</pre><pre>  class Graph<br>  {<br>  public:<br>    Graph(vector&lt; Node &gt; nodes) : nodes(nodes);</pre><pre>  private:<br>    vector&lt; Node &gt; nodes; // All nodes contained in the graph<br>  };</pre><p>Let’s create a bidirectional graph!</p><pre>typedef Node&lt; string &gt; NodeT; // We choose to store the name&#39;s node</pre><pre>  auto graph = Graph({<br>                  NodeT(&quot;Globo&quot;, {1, 2, 3}),<br>                  NodeT(&quot;Whisky&quot;, {0}),<br>                  NodeT(&quot;Hybesis&quot;, {0, 1}),<br>                  NodeT(&quot;Boudou&quot;, {1, 2})});</pre><blockquote><strong>Yup, that’s it!</strong><br>Great. Since we have all we need, let’s define some useful methods.</blockquote><pre>// Manipulations<br>  int Insert(Node node);                         // Insert a node<br>  void Connect(int idxA, int idxB, bool isBoth); // Add a connection</pre><pre>  // Return the node&#39;s degree<br>  int GetDegree(int idx);      <br>        <br>  // Return all the outgoing connections from a node<br>  set&lt; int &gt; GetNeighbors(int idx);</pre><h3>Manipulations</h3><h3>Insert / Connect</h3><pre>  // Insert a new node and return it&#39;s id<br>  int Insert(Node data)<br>  {<br>    nodes.push(data);<br>    return nodes.size() - 1;<br>  }</pre><pre>  // Connect two nodes together<br>  void Connect(int idxA, int idxB, bool isBoth)<br>  {<br>    [...] // Checks indexes validity<br>    nodes[idxA].insert(idxB);<br>    if (isBoth) nodes[idxB].insert(idxA);<br>  }</pre><blockquote><strong>Quite easy, right?!</strong></blockquote><h3>Node Information</h3><h3>GetDegree / GetNeighbors</h3><pre>// Return the degree of a node (number of connections)<br>  int GetDegree(int idx)<br>  {<br>    [...] // Checks index validity<br>    return node[idx].neighbors.size();<br>  }</pre><pre>  // Get all outgoing connections of a node<br>  set&lt; int &gt; GetNeighbors(int idx)<br>  {<br>    [...] // Checks index validity<br>    return nodes[idx].neighbors;<br>  }</pre><blockquote>From this one, we can easily find out the total number of nodes connected to any node, and what these nodes are.</blockquote><h3>Graph Traversal</h3><blockquote>Let’s finish the coding by implementing a graph traversal. We will use a simple <a href="https://hurna.io/en/academy/algorithms/maze_pathfinder/bfs.html">BFS (Breadth First Search) strategy</a> straight from our Graph definition.</blockquote><pre>  // We use the bool &quot;isVisited&quot; to keep track of our traversal<br>  typedef Node&lt; bool &gt; NodeT;</pre><pre>  BFS(int startIdx)<br>  {<br>    auto start = nodes.data()[startIdx];  // Get the start node<br>    start-&gt;data = true;                   // Set node to be visited<br>    Queue queue(start);                   // Put node in the queue</pre><pre>    // While there is node to be handled in the queue<br>    while (!queue.empty())<br>    {<br>      // Handle node in the front<br>      auto node = queue.pop();</pre><pre>      // Take neighbors, mark as visited, and add to the queue<br>      auto neighbors = node-&gt;GetNeighbors();<br>      for (auto it = neighbors.begin(); <br>           it !== neighbors.end(); ++it)<br>      {<br>        auto linkedNode = nodes.data()[*it]; <br>        if (linkedNode-&gt;data) continue;      // Check if visited</pre><pre>        linkedNode-&gt;data = true;    // Set visited<br>        queue.push(linkedNode);     // Add to the queue<br>      }<br>    }<br>  }</pre><blockquote>Voila ! You can code a GPS now.</blockquote><h3>What if I want to add some weights (distances)?</h3><p>Adjacency Lists can also be used to represent a weighted graph. The weights of edges (links / connections) can be represented as lists of pairs:</p><pre>[<br>  [{ &quot;idx&quot;: 1, &quot;weight&quot;: 4 }, { &quot;idx&quot;: 2, &quot;weight&quot;: 2 }, <br>   { &quot;idx&quot;: 3, &quot;weight&quot;: 0 }],<br>  [{ &quot;idx&quot;: 0, &quot;weight&quot;: 3 }, { &quot;idx&quot;: 2, &quot;weight&quot;: 3 }],<br>  [{ &quot;idx&quot;: 0, &quot;weight&quot;: 4 }, { &quot;idx&quot;: 1, &quot;weight&quot;: 4 }],<br>  [{ &quot;idx&quot;: 0, &quot;weight&quot;: 10 }]<br>]</pre><blockquote>Try to implement this yourself as an exercise and try to find find the shortest path in this new graph. You may use a slightly modified version of our BFS algorithm seen above.</blockquote><h3>In Short</h3><p>Adjacency Lists and Adjacency Matrix are the two most commonly used representations of a graph. Let’s compare them shortly with:</p><p>- <strong>N</strong> the number of nodes.<br>- <strong>M</strong> the number of edges.<br>- <strong>degree(i)</strong> denotes the number of outgoing connections from node i.</p><blockquote><strong>Adjacency Lists</strong><br>Memory space: <strong>O(N + M)</strong><br>Check if two nodes are connected: <strong>O(degree(i))</strong><br>Get all outgoing connections of a node: <strong>O(1)</strong></blockquote><blockquote><strong>Adjacency Matrix</strong><br>Memory space: <strong>O(N * N)</strong><br>Check if two nodes are connected: <strong>O(1)</strong><br>Get all outgoing connections of a node: <strong>O(N)</strong></blockquote><h3>Implementations Performances</h3><p>For the most courageous, we will finish by seeing some trade-off between using STL’s vector, set, or list to represent the nodes (vertices) and the connections (edges). Let’s first review some main differences:</p><blockquote><strong>Set</strong><br>A set is automatically sorted<br>Insert/Delete/Find: <strong>O(log n)</strong></blockquote><blockquote><strong>Unordered Set</strong><br>An unordered set is not sorted<br>Insert/Delete/Find: <strong>O(1)</strong></blockquote><blockquote><strong>Vector</strong><br>A vector is not sorted<br>Insert/Delete/Find: <strong>O(n)</strong></blockquote><blockquote><strong>Linked List</strong><br>A list is not sorted<br>Find takes <strong>O(n)</strong><br>Insert/Delete: <strong>O(1)</strong></blockquote><p>Based on this, if you want to <strong>keep your edges or vertices sorted</strong>, you should probably go with <strong>a set</strong>. If you want a <strong>very fast search time</strong>, you should go with an <strong>unordered_set</strong>.</p><p>If find time is not that important, you can go with a list or a vector. But there is one more important reason that one might <strong>use a vector/list instead</strong> of set, which is <strong>representing multi-graph</strong>.</p><blockquote><strong>A multi-graph is similar to a graph, but it can have multiple edges between two nodes.</strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e1befa93285" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/handling-graphs-with-adjacency-lists-7e1befa93285">Handling Graphs With Adjacency Lists</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pull Request Workflow with Git — 6 steps guide]]></title>
            <link>https://medium.com/@urna.hybesis/pull-request-workflow-with-git-6-steps-guide-3858e30b5fa4?source=rss-131ab5a2007------2</link>
            <guid isPermaLink="false">https://medium.com/p/3858e30b5fa4</guid>
            <category><![CDATA[gitflow]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[workflow]]></category>
            <category><![CDATA[rebase]]></category>
            <category><![CDATA[pull-request]]></category>
            <dc:creator><![CDATA[Hybesis - H.urna]]></dc:creator>
            <pubDate>Tue, 19 May 2020 11:35:27 GMT</pubDate>
            <atom:updated>2020-07-26T21:05:37.132Z</atom:updated>
            <content:encoded><![CDATA[<h3>Pull Request Workflow with Git — 6 steps guide</h3><h3>Introduction</h3><p>A pull request flow is a lightweight, 6 steps, branch-based workflow. <br>Note: this guide some quotations from <a href="https://guides.github.com/">GitHub Guides</a> (Open Source).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0frm6MvNkCtuQEMg.png" /></figure><blockquote><strong>Here is an overview of the pull request workflow:<br>0. “Pull” the changes to your local machine (get the most recent base)<br>1. Create a “branch” (version)<br>2. Commit the changes<br>3.a Push your changes<br>3.b Open a “pull request” (propose changes)<br>4. Discuss and review your code<br>5. Rebase and tests<br>6. “Merge” your branch to the master branch</strong></blockquote><h3>1. Create a branch</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AbFP4SPZZa_3RVHW.png" /></figure><h3>Branches</h3><p>The <em>master</em> branch is the “default” branch when you create a repository. Use other branches for development and merge them back to the master branch upon completion.</p><p>create a new branch named “feature_x” and switch to it using<br>git checkout -b feature_x<br>a branch is <em>not available to others</em> unless you push the branch to your remote repository<br>git push origin &lt;branch&gt;</p><blockquote>Note : Git comes with built-in GUI tools for browsing — <strong>gitk</strong>. We recommend you to use it in order to get a good overview of your branches. You just have to launch it within your repository:<br>gitk</blockquote><blockquote>Tip : <strong>There’s only one rule: anything in the master branch is always deployable.</strong></blockquote><blockquote>Because of this, it’s extremely important that your new branch is created off of master when working on a feature or a fix. Your branch name should be descriptive (e.g., refactor-authentication, build-maze-visualizer, use-embedded-format).</blockquote><h3>2. Commits</h3><p>This process of adding commits keeps track of your progress as you work. Commits also create a transparent history of your work that others can follow to understand what you’ve done and why. Each commit has an associated commit message, which is a description explaining why a particular change was made.</p><p><strong>Furthermore, each commit is considered a separate unit of change. This lets you roll back changes if a bug is found, or if you decide to head in a different direction.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fCDhhg4mTgqDxXzt.png" /></figure><h3>Add &amp; commit</h3><p>You can propose changes (add it to the <strong>Index</strong>) using<br>git add &lt;filename&gt;<br>git add *<br>To actually commit these changes use<br>git commit -m &quot;Commit message&quot;</p><blockquote>Note : Git comes with built-in GUI tools for committing — <strong>git-gui</strong>. We recommend you to use it in order to avoid being struggled with the command line. You just have to launch it within your repository:<br>git gui</blockquote><blockquote>Tip : Commit messages are important, they describe your code history. By writing clear commit messages, you can make it easier for other people to follow along and provide feedback.</blockquote><h3>3.a Push your changes</h3><p>A branch is <em>not available to others</em> unless you push the branch to your remote repository<br>git push origin &lt;branch&gt;</p><h3>3.b Open a Pull Request</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7lSbC78AN6pAgaaB.png" /></figure><p>Pull Requests initiate discussion about your commits. Anyone can see exactly what changes would be merged if they accept your request.</p><p>You can open a Pull Request at any point:<br>when you have little or no code but want to share some screenshots or general ideas,<br>when you’re stuck and need help or advice,<br>or when you’re ready for someone to review your work.</p><blockquote>Tip : <strong>Pull Requests are useful for contributing to open source projects and for managing changes to shared repositories.</strong></blockquote><h3>4. Discuss and review your code</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pcvtS8aN4qhzfDYC.png" /></figure><p>Once a Pull Request has been opened, the person or team reviewing your changes may have questions or comments (the most often through your git host platform). Perhaps the coding style doesn’t match project guidelines, the change is missing unit tests, or maybe everything looks great and props are in order. Pull Requests are designed to encourage and capture this type of conversation.</p><p>You can also continue to push to your branch in light of discussion and feedback about your commits. If someone comments that there is a bug in the code, you can fix it in your branch and push up the change.</p><h3>5. Rebase and tests</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_KV_rWe23HSBrj3U.png" /></figure><p>Once your pull request has been reviewed and the branch passes your tests, you can rebase your branch on master (it will use the most recent version of the code base) in order to test all the changes together (production).</p><h3>Rebase</h3><p>To take all the changes that were committed on master and replay them on the current branch.<br>git rebase master<br>This operation works by resetting the current branch to the same commit as master, and applying each commit of the current branch.</p><blockquote><strong>If your branch causes issues, you should fix it in your branch before merging with master.</strong></blockquote><h3>6. Merge</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cWYTGbMdR-qJiOks.png" /></figure><h3>Merge</h3><p>Now that your changes have been verified in production, it is time to merge your code into the master branch.<br>git checkout master<br>git merge &lt;branch&gt; --no-ff</p><h3>— no-ff | No Fast Forward</h3><p>The — no-ff option is useful when you want to have a clear notion of your feature branch. <strong>So you treat a feature branch with a bunch of commits as a single unit</strong>, and merge them as a single unit. It is clear from your history when you do feature branch merging with — no-ff.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/0*2_7qU8BvZwfLZuDx.png" /></figure><h3>Tag &amp; Version</h3><p>It is recommended to create tags for software releases. You can create a new tag named <em>Hurna v1.3.0</em> by executing<br>git tag -a v1.3.0 -m &quot;Hurna v1.3.0&quot;</p><p>This makes it easy to keep track of your versions and rollback if needed.</p><blockquote><strong>Find playgrounds and more about git at </strong><a href="https://hurna.io/academy/git/index.html">https://hurna.io/academy/git/index.html</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3858e30b5fa4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Git from scratch — 5 steps guide]]></title>
            <link>https://medium.com/@urna.hybesis/git-from-scratch-5-steps-guide-8943f19c62b?source=rss-131ab5a2007------2</link>
            <guid isPermaLink="false">https://medium.com/p/8943f19c62b</guid>
            <category><![CDATA[git]]></category>
            <category><![CDATA[version-control]]></category>
            <category><![CDATA[guidelines]]></category>
            <category><![CDATA[project-management]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <dc:creator><![CDATA[Hybesis - H.urna]]></dc:creator>
            <pubDate>Sat, 16 May 2020 09:09:31 GMT</pubDate>
            <atom:updated>2020-05-16T09:09:31.939Z</atom:updated>
            <content:encoded><![CDATA[<h3>Git from scratch — 5 steps guide</h3><h3>Introduction</h3><p>“<strong>Git is a free and open source distributed version control system</strong> designed to handle everything from small to very large projects with speed and efficiency. Git is easy to learn and has a tiny footprint with lightning fast performance.” (Git)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Mv3eDegTiE3QZTBm.png" /></figure><blockquote>But first thing first : what is a “version control system”, and why should we care?</blockquote><p>A version control system (VCS) tracks changes to files. As we <strong>modify files, the system records and saves each change within an history</strong>. This allows to restore a previous version of your code at any time. Using a VCS also generally means that <strong>if we screw things up or lose files, we can easily recover to any checkpoint</strong>.</p><p>In a collaborative environment, it is common for several developers to share and work on the same source code. While some developers will be fixing bugs, others will be implementing new features, etc. Git is the standard system used to manage all of this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VLnmJduLEc4VoRDY.png" /></figure><p>In short, a version control system like <strong>Git is essential for all kind of programming and software development</strong>. It makes it easy to:</p><p>- Keep track of code history<br>- See which changes were made<br>- See why were changes made<br>- See who made which changes<br>- Collaborate on code as a team<br>- Deploy to staging or production</p><blockquote>We will learn here Git from essentials like repositories, branches, commits, and Pull Requests to more advanced topics such as workflow, statistics, automatic build integration and how to collaborate with other developers.</blockquote><h3>What if I don’t use it?</h3><p>I am sure any of us has already been doing some file renaming to keep track of different versions, as for instance : “resume”, “resume_v2”, “resume_062018”…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/0*u2DR4xtcfGdHphhl.png" /></figure><p>In other words, any of us has already been <strong>stuck to manually save multiple versions of files</strong> using different names. Renaming a file also <strong>doesn’t give us any context</strong> as to what changes were made or who they were made by. When multiple team members edit the same file, <strong>overwriting occurs</strong> and it starts being impossible to keep up with the latest file version.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/0*9lEvQDTj5YUMGPHD.png" /></figure><p><strong>This problem already occurs for a unique file. I let you imagine how messy it can be with thousands of them.</strong></p><h3>Why using Git in particular?</h3><blockquote><strong>The very short answer would be : Git is the most widely used version control system in the world and is considered the modern standard for software development.</strong></blockquote><p>Unlike older centralized version control systems such as SVN and CVS, <strong>Git is distributed: every developer has the full history of their code repository locally.</strong> Thus, if any server dies, and these systems were collaborating via that server, <strong>any of the client repositories can be copied back up to the server to restore it</strong>. Every clone is really a full backup of all the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Md4GV5vaHJnWEzSH.png" /></figure><p>Git also has <strong>excellent support for branching, merging, and rewriting repository history, which has lead to many innovative and powerful workflows and tools</strong>. Pull requests are one such popular tool that allow teams to collaborate on Git branches and efficiently review each others code.</p><blockquote><strong>Great, since we know for what and why we are using Git. Let’s get started!</strong></blockquote><h3>Simple guide — 5 steps</h3><p>This guide is a simple and practical introduction to start working with git from scratch. Here, we will go straight to the point. This step by step guide to a Git workflow aims to help give an introductory overview for managing any project.</p><blockquote><strong>Let’s get started on using Git now.</strong></blockquote><h3>1. Installation</h3><p><a href="https://git-scm.com/book/en/Getting-Started-Installing-Git">Git for Linux</a></p><p><a href="https://git-scm.com/download/mac">Git for OSX</a></p><p><a href="https://msysgit.github.io/">Git for Windows</a></p><blockquote>Verify if Git is installed by using the following command in the command prompt:<br>git --version</blockquote><h3>2. Create or get a repository</h3><blockquote>To start working on a Git repository, you have the choice to either create a new one or use an existing one (from GitHub for instance).</blockquote><h3>Create a new repository</h3><p>create a new directory, create a directory and perform a<br>git init<br>inside to create a new git repository.</p><h3>Checkout a repository</h3><p>create a working copy of a local repository by running the command<br>git clone /path/to/repository<br>when using a remote server, your command will be<br>git clone username@host:/path/to/repository</p><h3>3. Save our changes</h3><p>Our local repository consists of three “trees” maintained by git.<br>The first one is your Working Directory which holds the actual files.<br>The second one is the Index which acts as a staging area.<br>And finally, the HEAD which points to the last commit we have made.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/0*1rjdPdGekYWIE0q6.png" /></figure><h3>A. Commit</h3><blockquote>Note : Git comes with built-in GUI tools for committing — <strong>git-gui</strong>. We recommend you to use it in order to avoid being struggled with the command line. You just have to launch it within your repository:<br>git gui</blockquote><h3>Add &amp; commit</h3><p>You can propose changes (add it to the <strong>Index</strong>) using<br>git add &lt;filename&gt;<br>git add *<br>This is the first step in the basic git workflow. To actually commit these changes use<br>git commit -m &quot;Commit message&quot;<br>Now the file is committed to the <strong>HEAD</strong>, but not in your remote repository yet.</p><h3>B. Push</h3><blockquote>First thing first, we need a host (such as Github, Gitlab, Bitbucket…) to put it online. If it has not been done yet, just create an account on one of this platform.</blockquote><h3>Pushing changes</h3><p>Your changes are now in the <strong>HEAD</strong> of your local working copy. To send those changes to your remote repository, execute<br>git push origin master<br>Change <em>master</em> to whatever branch you want to push your changes to.</p><p>If you have not cloned an existing repository and want to connect your repository to a remote server, you need to add it with<br>git remote add origin &lt;server&gt;<br>Now you are able to push your changes to the selected remote server</p><blockquote>The full workflow results as the following:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/0*b_MxcArzDXioI-RL.png" /></figure><h3>4. Branching</h3><h3>A. Branches</h3><p>Branching allows each developer to branch out from the original code base and isolate their work from others. It also helps Git to easily merge versions later on.</p><p>Imagine that you are working with your colleagues on the same file. There is a solid chance that someone will, at least partially, overwrite one other’s work. We can avoid that by branching in order to isolates our work from that of other team members.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/0*ZbIitqS4lLuNGlST.png" /></figure><blockquote><strong>In short, a Git branch is an independent line of development.</strong><br>Note: each node on the image above represents a commit.</blockquote><h3>Branches</h3><p>The <em>master</em> branch is the “default” branch when you create a repository. Use other branches for development and merge them back to the master branch upon completion.</p><p>create a new branch named “feature_x” and switch to it using<br>git checkout -b feature_x<br>switch back to master<br>git checkout master<br>and delete the branch again<br>git branch -d feature_x<br>a branch is <em>not available to others</em> unless you push the branch to your remote repository<br>git push origin &lt;branch&gt;</p><blockquote>Note : Git comes with built-in GUI tools for browsing — <strong>gitk</strong>. We recommend you to use it in order to get a good overview of your branches. You just have to launch it within your repository:<br>gitk</blockquote><h3>B. Update &amp; Merge</h3><h3>update &amp; merge</h3><p>To update your local repository to the newest commit, execute<br>git pull<br>in your working directory to <em>fetch</em> and <em>merge</em> remote changes.<br>to merge another branch into your active branch (e.g. master), use<br>git merge &lt;branch&gt;<br>in both cases git tries to auto-merge changes. Unfortunately, this is not always possible and results in <em>conflicts</em>. You are responsible to merge those <em>conflicts</em> manually by editing the files shown by git. After changing, you need to mark them as merged with<br>git add &lt;filename&gt;<br>before merging changes, you can also preview them by using<br>git diff &lt;source_branch&gt; &lt;target_branch&gt;</p><h3>Reverting changes</h3><blockquote>If you instead want to drop all your local changes and commits, fetch the latest history from the server and point your local master branch at it like this:</blockquote><h3>Replace local changes</h3><p>git fetch origin<br>git reset --hard origin/master</p><h3>5. Extras</h3><h3>Tag &amp; Version</h3><p>It is recommended to create tags for software releases. You can create a new tag named <em>Hurna v1.3.0</em> by executing<br>git tag -a v1.3.0 -m &quot;Hurna v1.3.0&quot;</p><h3>Log</h3><p>in its simplest form, you can study repository history using<br>git log<br>You can add a lot of parameters to make the log look like what you want. To see only the commits of a certain author:<br>git log --author=michael-jeulinl<br>To see a very compressed log where each commit is one line:<br>git log --pretty=oneline<br>Or maybe you want to see an ASCII art tree of all the branches, decorated with the names of tags and branches:<br>git log --graph --oneline --decorate --all<br>See only which files have changed:<br>git log --name-status<br>These are just a few of the possible parameters you can use. For more, see<br>git log --help</p><blockquote>Wonderful! If you get this far, you master everything you need to manage a project and its versions. The next courses are about putting everything into advanced practices.</blockquote><blockquote><strong>Here is a list of some more Git commands to get you going with Git in a day-to-day workflow: </strong><a href="https://hurna.io/academy/git/general_commands.html">https://hurna.io/academy/git/general_commands.html</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8943f19c62b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Euclidean Division explained to Kids]]></title>
            <link>https://medium.com/@urna.hybesis/euclidean-division-explained-to-kids-33a9c7bd136b?source=rss-131ab5a2007------2</link>
            <guid isPermaLink="false">https://medium.com/p/33a9c7bd136b</guid>
            <category><![CDATA[divide]]></category>
            <category><![CDATA[gcd]]></category>
            <category><![CDATA[euclidean-algorithm]]></category>
            <category><![CDATA[euclid]]></category>
            <category><![CDATA[long-division]]></category>
            <dc:creator><![CDATA[Hybesis - H.urna]]></dc:creator>
            <pubDate>Thu, 30 Apr 2020 10:14:36 GMT</pubDate>
            <atom:updated>2020-04-30T10:14:36.324Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In our previous courses, we have seen how to perform the four fundamental operations (add, subtract, multiply and divide) on both <a href="https://hurna.io/academy/mathematics/numbers_operations/naturals.html">natural numbers</a> and <a href="https://hurna.io/academy/mathematics/numbers_operations/integers">integers</a>. However, we didn’t handle more complex cases such as when it was not dividing things up exactly. This is the subject of this important course: <strong>the Euclidean division — or division with remainder</strong>.</p><blockquote>Don’t worry, the name and importance hide something very easy to understand and perform ;)</blockquote><p>Euclidean division, and algorithms to compute it, are fundamental for many questions such as for finding the <strong>greatest common divisor (GCD)</strong> or in modular arithmetic — <strong>modulo operation</strong> (used absolutely everywhere in computer science: from website to cryptography through video games).</p><blockquote>But first, a small reminder about the division!</blockquote><h3>Reminder — Dividing</h3><p><strong>The division allows us to calculate the sharing problems, it is the opposite of multiplying.</strong></p><blockquote>Example:<br>There are 12 blue candies, and 4 friends want to share them, how do we divide the candies?</blockquote><p>The answer may seem evident: if each friend takes 3 candies, we are all good. <strong>Division is splitting into equal parts or groups. It is the result of “fair sharing”.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qy4mLsNVLCGATLzu.png" /></figure><p>Note:<br>As we said, another way to <strong>think of division is as the opposite of multiplication</strong>. Taking this example we got:</p><p>→ 12 / 4 = 3 (we gives 3 candies to each of us)</p><p>Now if we invert the operation using the result, we replace the ‘=’ with a ‘x’ sign and the ‘/’ with an ‘=’ sign:</p><p>→ 12 = 3 x 4 (if 3 candies are given to each of us, we shared a total of 12 candies)</p><blockquote>This is, indeed, a mathematical definition of the division: <br><em>a / b = a ∗ 1 / b</em></blockquote><blockquote>Using multiplication is a great way to check our division and master our math tests. But remember this rule, it is the only one to know when dealing with division:</blockquote><blockquote><strong>We never divide by 0!</strong></blockquote><h3>But… Sometimes it does not fit perfectly!</h3><blockquote>Let’s deal with it!</blockquote><h3>The Remainder</h3><p>As we have seen, division is breaking a number up into an equal number of parts, but… there may be something left over. Let’s go back on our previous example, however, this time the <strong>4 friends have 13 (one more than before) blue candies to share</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*V0Aiwc1NGkZ73jBr.png" /></figure><blockquote>We can see that there is <strong>1 left over; we call that the Remainder</strong>.<br>Note: it may eventually be possible to cut the remaining candy in four (a quarter — 1/4 — of candy for each), but this is addressed in the course dealing with <a href="https://hurna.io/academy/mathematics/fraction.html">Fractions</a>.</blockquote><blockquote>We will now learn how to perform all divisions (even with large numbers) by hand. But first, a quick overview of the vocabulary.</blockquote><h3>Dividend, Divisor, Quotient and Remainder</h3><p>Each part of a division has a name:</p><p>— <strong>Dividend:</strong> The dividend is the number you are dividing up.<br> — <strong>Divisor:</strong> The divisor is the number you are dividing by.<br> — <strong>Quotient:</strong> The quotient is the main result (the number of candies you can give to each one).<br> — <strong>Remainder:</strong> The left over.</p><p>For instance: 13 (dividend) ÷ 4 (divisor) = 3 (quotient) ‘R’1 (remainder)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/0*KaiNez2iwYSFp0-J.png" /></figure><blockquote>Great, I think we are now fully ready to tackle the process!</blockquote><h3>Euclidean division</h3><p>To perform a division by hand, every student learns (without knowing) an algorithm which is one of the oldest algorithms in use (it appeared in Euclid’s Elements around 300 BCE).</p><blockquote>We will decompose the process step-by-step (only 2 steps to repeat) through an example: <strong>533 ÷ 4</strong>.</blockquote><blockquote>Here is the color legend used:</blockquote><blockquote>Red: the number we will try to divide by our divisor.<br>Blue: the divisor, how many of them do we have within the red number?<br>Green: the amount of divisor found within the red number.<br>Yellow: subtracting ‘Blue x Green’ from the red number.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*OWAixR6tsoyVjIVaJkDASg.png" /></figure><blockquote><strong>Now, we just repeat with the process with the result of the subtraction as the dividend.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*Mfi_C_WRUHXSlU18JPC4PA.png" /></figure><blockquote>And finally…</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*vHRsU-XI4Xih6H2BiebD4Q.png" /></figure><blockquote>We found out that: <strong>533 ÷ 4 = 133, ‘R’1</strong><br>We can also say that: <strong>533 = 4 x 133 + 1</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/0*Uu5o9aOd5LBBgPMD.png" /></figure><blockquote><strong>Woaw, this is very handy!</strong></blockquote><h3>Euclid’s algorithm — always find the GCD</h3><p>To always find the GCD we will use <strong>Euclid’s algorithm</strong>:</p><p>- Perform the Euclidean division of the greatest number (noted a) of the fraction on the smallest number (noted b) and keep the rest (noted r).</p><p>- As long as the rest is different from 0, we reiterate the division replacing a by b and b by r.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*x8ReHtrp4Ug2DYbv.png" /></figure><p>We will then be able to write:<br>1053=81 * 13<br>325=25 * 13</p><blockquote>We will use the GCD a lot starting with mastering the <a href="https://hurna.io/academy/mathematics/fraction.html">fractions</a> whether to simplify them or to perform operations.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33a9c7bd136b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Illustrated guide to terms used daily in programming]]></title>
            <link>https://levelup.gitconnected.com/illustrated-guide-to-terms-used-daily-in-programming-1c760dc067d7?source=rss-131ab5a2007------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c760dc067d7</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[illustration]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[vocabulary]]></category>
            <dc:creator><![CDATA[Hybesis - H.urna]]></dc:creator>
            <pubDate>Fri, 17 Apr 2020 08:27:24 GMT</pubDate>
            <atom:updated>2020-04-25T15:51:25.513Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Here is a glossary of many terms used every day by tech people and programmers; this is a light and general glossary of many terms. Definitions are kept as simple and short as possible.</strong></p><blockquote>This may be used as a first overview of the programming world. This glossary is also a good fit if you ever wanted to be able to understand and communicate with developers or any other people working on digital projects.</blockquote><h3>Back End</h3><p>The back-end, or the “server-side”, is basically everything that is behind the scene. Systems have all kinds of logic that happen in the background that make them work: data needs to be stored and retrieved, business logic needs to be followed, results need to be calculated… <strong>For a website or web application, this refers to everything the user can’t see in the browser, like databases and servers.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*RAsNfBu0Gc9kKWgS.png" /></figure><h3>Command Line Interface (CLI)</h3><p>A Command Line Interface is used to process commands to a computer program in the form of lines of text. They are opposed to GUI (Graphic User Interface). We use it all the when using the Terminal (e.g. Unix console), for instance using Git:</p><pre>$ git clone <a href="https://github.com/Hurna/Hurna-Core.git">https://github.com/Hurna/Hurna-Core.git</a></pre><h3>Code Review</h3><p>Code review is a phase in the software development process in which the authors of code and peers review the code to make sure that the overall code is healthy, does not contain bug, and is improving over time.</p><blockquote>Code reviews are classless: being the most senior person on the team does not imply that our code does not need review.</blockquote><h3>Continuous Delivery — Continuous Integration(CI/CD)</h3><p>For big apps, pushing to production requires a lot of steps. Continuous integration and continuous delivery (CI/CD) is the activity of automated build, integration, and testing processes. It allows to release continuously new updates. Managing this process is often the work of people called DevOps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/0*tHegdei0XvVyi2m6.png" /></figure><h3>Front End</h3><p>For an application, the Front End is the part that is exposed to the user. The front end of a website is the part that users interact with. Everything that you see when you’re navigating around the Internet, from fonts and colors to dropdown menus and sliders, is a combo of HTML, CSS, and JavaScript being controlled by your computer’s browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*_ppoeYll1lMe8fw0.png" /></figure><h3>Middleware</h3><p>A Middleware is a software that bridges gaps between other applications, tools, and databases in order to provide unified services to users. It is commonly characterized as the glue that connects different software platforms and devices together.</p><p>In web development, it often lies between the part of the code that receives the request and the other part of the code that do database updates, generates the response, etc.</p><h3>Refactoring</h3><p>Refactoring is a disciplined technique for restructuring an existing body of code, altering its internal structure without changing its external behavior.</p><p>The basic purpose of code refactoring is to make the code more efficient and maintainable. This is key in reducing technical cost since it’s much better to clean up the code now than pay for costly errors later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AK_FkGsz3pIzIxBx.png" /></figure><h3>Unit Testing (UT)</h3><p>Unit testing is an <strong>essential part of developing software</strong> applications. Also called component testing, it is all about <strong>isolating one unit of code to verify that it’s working as it should be</strong>.</p><blockquote>Unlike many types of testing, UTs are usually done by the developer of the code itself. If you’re not doing unit testing now, I recommend you to get started on it.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/0*6Ion7nqaqfgPcOtf.png" /></figure><p>Another way to look at unit testing is that we write the tests first. This is known as Test-Driven Development (TDD for short). TDD brings additional advantages:<br>- We don’t write speculative “I might need this in the future” code — just enough to make the tests pass to cover our API.<br>- By writing the test first, we are forced into thinking about how you want to call the code, which usually improves the design of the code in the long run.</p><h3>Algorithm</h3><p>Everything that we do with a computer relies in some way on an algorithm. Any software (even the most advanced Artificial Intelligence) are only algorithms put together with some structured data (cf. below).<br>That’s it: <a href="https://hurna.io/academy/algorithms/index.html"><strong>Algorithms</strong></a><strong> + </strong><a href="https://hurna.io/academy/data_structures/index.html"><strong>Data Structures</strong></a><strong> = Software.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bezKHaxTdW4rkB66.png" /></figure><p>In other words, it is a list of instructions, procedures, or formula that solves a problem… It can be a code to sort search results efficiently, a code to find the shortest route between A and B on a map, a formulal to encrypt and decrypt sensitive information, etc.</p><h3>Data Structure</h3><p><a href="https://hurna.io/academy/data_structures/index.html"><strong>Data structures</strong></a><strong> are the way we can store and retrieve data</strong>, they represent the knowledge to be organized in memory. No matter what problem are we solving, in one way or another we have to deal with them !</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*edgoC6GSpRdrZcmk.png" /></figure><h3>Dead Code</h3><p>Dead code is any section of the codebase that is never used by the application.</p><h3>Infinite loop — Endless loop</h3><p>An infinite loop is a <strong>sequence of instructions that will continue endlessly</strong>, unless an external intervention occurs. It may be intentional, but most of the time, our breaking condition doesn’t work. The result of such infinite loop often results in a application that freezes (and consume most of our CPU which may then lead to general lags) or even crash.</p><h3>Functional Programming</h3><p>Functional programming or FP is a programming paradigm. This is a style of building software applications. Some of its principles are the way of building a program by composing pure functions, avoiding shared state, mutable data, and side-effects.</p><h3>Garbage collection</h3><p>When a program is running, it uses the computer’s memory. Garbage collection does exactly what it says, it looks for <strong>memory that can’t be used by the program anymore and frees it</strong>, allowing this freed space to be used again.</p><h3>Memoization</h3><p>Memoization is a technique used to store, the result of a computationally expensive function by storing it in a cache. If the function is called later using the same arguments, the result is loaded from the cache rather than being recomputed, saving CPU resources.</p><blockquote><strong>In brief: Memoization is a way to remember what we already found.<br>It is used to lower a function’s time cost in exchange for space cost.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*t59LbgEhJO63Lp4S.png" /></figure><p>Where naive recursion falls short with Fibonacci: the tree above shows for each indice (root) the nodes to be computed (all of its children). The red nodes are showing useless computation which may instead use the results already computed by the blue ones.</p><blockquote>As a reminder the Fibonacci numbers are defined as follow:<br>F(0) = 0<br>F(1) = 1<br>F(n) = F(n−1) + F(n−2)</blockquote><h3>Parse</h3><p>The action of <strong>transforming data described textually into data stored within a data structure.</strong> When we fetch data from a web API, it is usually a JSON (just a string). We need to parse it, to transform it into an object, to manipulate data efficiently:</p><pre>// JSON data (stored as a string)<br>  {<br>    &quot;name&quot;: &quot;Maze Solver - Pathfinding&quot;,<br>    &quot;list&quot;: {<br>      &quot;a_star&quot;: &quot;A* (A-Star)&quot;,<br>      &quot;bfs&quot;: &quot;Breadth First Search&quot;,<br>      &quot;dfs&quot;: &quot;Depth First Search&quot;,<br>      &quot;dijkstra&quot;: &quot;Dijkstra&quot;<br>    }<br>  }</pre><pre>// JS manipulate data through an Object built from the string parse.<br>  const parsedData = JSON.parse(data);</pre><pre>  // parsedData is now an object and can be accessed as follows:<br>  parsedData.name;              // &quot;Maze Solver - Pathfinding&quot;<br>  parseData.list.forEach(...);  // Iterate over the list</pre><h3>Spaghetti code</h3><p>Spaghetti code is a slang used to describe a program’s <strong>source code that is difficult to read or follow</strong> by a human because of how the original programmer wrote the code. It can be caused by several factors, such as volatile project requirements, lack of programming style rules, and insufficient ability or experience of the programmer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hpr-_BIWmUf6N-WX.png" /></figure><h3>Class (Prototype) — Object (Instance)</h3><blockquote><strong>A class (prototype) is a template that defines object properties</strong> and may also describe object behavior.<br><strong>An object is an instance of a class.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/0*nlYCJRsCL9yZeu_t.png" /></figure><p>We can think of class as a sketch (prototype) of a car. It contains all the details about the number of tires, the doors, the color… Based on these descriptions we build a car, let’s say the Green car: this Green car is the object. As many cars can be made from the same prototype, we can create as many objects as we want from a class.</p><blockquote>Find more details in the <a href="https://hurna.io/academy/glossaries/function_class.html">‘Function — Class’ glossary</a>.</blockquote><h3>Constant</h3><p>A constant is a value or a <strong>variable with a value that will never change during the running time of the program</strong>. The keyword ‘const’ is used to define such data in most programming language:</p><pre>const auto lastName = &quot;CantBeChanged&quot;;</pre><h3>Data Structure</h3><p><a href="https://hurna.io/academy/data_structures/index.html"><strong>Data structures</strong></a><strong> are the way we can store and retrieve data</strong>, they represent the knowledge to be organized in memory. No matter what problem are we solving, in one way or another we have to deal with them !</p><blockquote>A data structure instance is an Object.</blockquote><h3>Null — Nullptr</h3><p>Null and NullPtr represent an intentional absence of a value.</p><pre>let uninstantiated = null; // JS</pre><pre>Car* lostPtr = nullptr; // C++</pre><h3>Pointer</h3><p>A pointer is a variable that holds a memory address where a value lives. As an analogy, a page number in a book’s index could be considered a pointer to the corresponding page.</p><blockquote>Pointers are the foundation of how computers allocate and deal with memory in hardware. They allow us to read and write directly in memory space.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*xJcC14vBiO7kIEXV.png" /></figure><h3>String</h3><p>A string is a sequence of characters used to represent text.</p><pre>const string = &quot;hello world&quot;;</pre><p>A string can be manipulated as an Array containing chars (cf. below).</p><h3>Primitives</h3><p>The primitive data type is the basic building block of data. They hold one single value. They represent a char, number, or boolean.</p><blockquote>Note: the actual range of primitive data types that is available is dependent upon the specific programming language that is being used (those are the most basic ones).</blockquote><h3>Boolean — bool</h3><p>A boolean has 2 possible values: true or false.</p><pre>bool truth = true;</pre><h3>Character — Char</h3><p>It stores a single character and requires a single byte of memory:</p><pre>const char letter = &#39;H&#39;;</pre><h3>Number — Integer (Int), Float…</h3><p>A numeric data type.</p><pre>const pi = 3.14; // :p</pre><h3>Undefined</h3><p>Undefined with JS is a primitive value automatically assigned to a variable that has just been declared or to the argument of a function that has not been provided.</p><h3>Formats</h3><h3>JSON</h3><p>JSON stands for JavaScript Object Notation. It is a way to format data so that it can be human readable, storable as a string and thus be transmitted from one place to another. It is most commonly used in web development.</p><pre>{<br>  &quot;id&quot; : 8,<br>  &quot;name&quot; : &quot;Globo&quot;,<br>  &quot;functions&quot; : [&quot;solver&quot;, &quot;player&quot;, &quot;teacher&quot;],<br>  &quot;isAvailable&quot; : true<br>}</pre><h3>XML</h3><p>XML stands for eXtensible Markup Language and was designed to store and transport data in a readable way for both humans and machines. Both XML and JSON have the same purpose.</p><h3>Argument — Parameter</h3><p>A <strong>parameter</strong> (or formal argument) is a <strong>variable in a function or method definition</strong>. When the function is called, the <strong>argument is the data we pass in the function call</strong>.</p><pre>int square(int number)  // number is the parameter<br>  { return number * number; }<br>  ---<br>  auto result = square(3); // 3 is the argument</pre><h3>Callback</h3><p><strong>A callback is a function that is passed as an argument to a function</strong>, which is expected to call back (execute) at a convenient time. This may for instance be to display information (as the number of lines) of a file once read.</p><pre>// Callback definition<br>  function displayCount(count)<br>  { console.log(&quot;File contains &quot; + count + &quot; lines.&quot;); }</pre><pre>  readFile(&quot;text.txt&quot;, displayCount); // Callback passed as argument</pre><blockquote>Callbacks are used everywhere in association with events in web development. In the case of an asynchronous call, call back can be executed when a response has been received.</blockquote><h3>Constructor</h3><p>The constructor is a method, inside a class, that is used to instantiate (create an instance) an object. It is automatically called when an object is built.</p><h3>Function</h3><p><strong>A function is a named section of a program that performs a specific task.</strong></p><pre>multiply(3, 3); // multiply is the function called</pre><p>Some programming languages make a distinction between a function, which returns a value, and a procedure, which performs some operation but does not return a value.</p><h3>Method</h3><p>A method is <strong>a function that belongs to a class</strong> or an object. It is bound to it, defined only within that scope of usage.</p><h3>Nested Function</h3><p>A nested function is <strong>a function contained inside of another function</strong>. It can be used to limit the scope of the inner function.</p><pre>function getSurfBoard(weather, size, height) {<br>  const boardList = getBoardForWeather(weather);</pre><pre>  // Nested function<br>  function filterBoardByBody(size, height) {...}<br>}</pre><h3>Recursive Function</h3><p>The term recursive describes a <strong>function or method that calls itself</strong>.</p><blockquote>Understanding how recursion works is a fundamental programming skill.</blockquote><pre>function fibonacci(number) {<br>  if (number === 0) return 0;<br>  if (number === 1) return 1;<br>  return fibonacci(number - 1) + fibonacci(number - 2);<br>}</pre><blockquote>As a reminder the Fibonacci numbers are defined as follow:<br>F(0) = 0<br>F(1) = 1<br>F(n) = F(n−1) + F(n−2)</blockquote><h3>Git — Version Control</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7KmTsc8BDVICTwTo.png" /></figure><p><strong>Git is an open-source distributed version control system designed to track changes and in computer files and coordinating work on those files among multiple people and locations.</strong> It is primarily used to allow programmers to work together in a codebase.</p><blockquote>One might never know all the git commands because they are numerous but there are some that every developer is expected to know to be able to collaborate with other developers.</blockquote><h3>Branch</h3><p>Branching allows each developer to branch out from the original code base and isolate their work from others. It also helps Git to easily merge versions later on.</p><p>Imagine that you are working with your colleagues on the same file. There is a solid chance that someone will, at least partially, overwrite one other’s work. We can avoid that by branching in order to isolates our work from that of other team members.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/0*2eZnV9d2rMur1Uot.png" /></figure><blockquote><strong>In short, a Git branch is an independent line of development.</strong><br>Note: each node on the image above represents a commit.</blockquote><pre>$ git checkout -b [branch name] // Create a new branch and switch to it</pre><h3>Commit</h3><p>To commit is the action of adding your changes to the local repository. It needs to be accompanied with a commit message that describes what this change is bringing to the code base:</p><pre>$ git commit -m &quot;This fix a bug in the code base&quot; // Commit changes</pre><blockquote>We recommend to use a GUI to manage commits, it gives us a better control on what we want to commit.</blockquote><pre>$ git gui // (git-gui)</pre><h3>Conflicts</h3><p>When working in Git, users can combine commits from two different branches through an action known as merging. Files are automatically merged unless the <strong>commits update the same line of code differently</strong>. In that case <strong>there is a conflict: which version of this line should be taken?</strong></p><blockquote>Merge conflicts can traditionally cause developers a lot of grief when working in the terminal. This is why we advise to use a GUI (such as meld) to resolve conflicts.</blockquote><h3>GitHub</h3><p>GitHub, Inc. is a US-based global company that provides hosting for software development version control using Git. This is the world’s largest open source platform. It is now a subsidiary of Microsoft, which acquired the company in 2018 for US$7.5 billion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WU6xESzB47ZuvHGo.png" /></figure><h3>Merge</h3><p>To merge one branch into another is the action of <strong>fusing 2 different versions of the project together</strong>. If you are done working on a branch named “my-feature”, you can merge it to master in order for the master branch to be updated with your work.</p><pre>$ git merge [source branch] [target branch] // Merge a branch into a target branch</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/0*ngShd3m0NLX-zBQL.png" /></figure><h3>Pull</h3><p>This is the action of <strong>updating your local version of a repository to the newest commit</strong>. Do not forget to do it before starting to work on something!</p><pre>$ git pull // Update local repository to the newest commit</pre><h3>Push</h3><p>This is the action of <strong>sending your commits to the remote repository</strong> (on GitHub or GitLab, for example).</p><pre>$ git push // Push changes to remote repository</pre><h3>Repository (repo)</h3><p>Take it as a folder that contains all the source files and tracks all the changes made, building a history over time. On Github, each project is a repo.</p><h3>Web — HTTP</h3><h3>CSS</h3><p>CSS stands for Cascading Style Sheets, it <strong>describes how HTML elements are to be displayed</strong>. It allows you to create great-looking web pages and control their layout all at once form external stylesheets (stored in CSS files).</p><blockquote>CSS saves a lot of work.</blockquote><pre>// All of the tag h1 are green and centered<br>  h1 {<br>    color: green;<br>    text-align: center;<br>  }</pre><h3>Document Object Model (DOM)</h3><p>The <strong>HTML</strong> we write is parsed by the browser and <strong>turned into the DOM (Object), which is essentially an API to the page</strong> that allows to read and manipulate the page’s content, structure, and styles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/0*hW5QktXx3T5Oms56.png" /></figure><blockquote>With the DOM, JavaScript gets all the power it needs to manipulate our pages dynamically.</blockquote><h3>Event, Event Listener</h3><p>Clicking, scrolling, pressing a key on our keyboard are what is called: “event”. There are a lot of them. On a website, we might want to listen to them by creating an event listener in order to do form validation, react to a click on a button, etc.</p><h3>HTML (Hypertext Markup Language)</h3><p>HTML (Hypertext Markup Language) is the code that is used to structure a web page and its content. HTML is not a programming language; it is the <strong>standard markup language used to create web pages and web applications</strong>. This markup uses tags ‘&lt;&gt;’ to tell a web browser how to display text, images and other forms of multimedia on a webpage.</p><h3>HTTP</h3><p><strong>HTTP is a protocol which allows the fetching of resources, such as HTML documents.</strong> It is the foundation of data exchange on the Web and it is a client-server protocol, which means requests are initiated by the recipient, usually throughout he Web browser. A complete document is constructed (or fetched) on the server side and then sent to the useer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*jJCuPAAB0yO9AMbQ.png" /></figure><h3>HTTPS</h3><p>Hypertext transfer protocol secure (HTTPS) is the secure version of HTTP. HTTPS is encrypted in order to increase security of data transfer. This is particularly important when users transmit sensitive data, such as by logging into a bank account, email service, or health insurance provider.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/0*-UqmmWdmxlUyQYGK.png" /></figure><p>Any website, especially those that require login credentials, should use HTTPS. In modern web browsers, websites that do not use HTTPS are marked differently than those that are. Look for a green padlock in the URL bar to signify the webpage is secure.</p><h3>JWT</h3><p>JWT or JSON Web Token is a standard used to create secure access tokens for an application.</p><p>In the case of a web application, the server will generate a token that certifies the user identity and send it to the Client. The Client will, for every subsequent request, attach the JWT to it so the server knows the request comes from a particular identity.</p><p>VOILA ! Don’t hesitate to visit H.urna Academy to get deeper knowledge for each of these concepts: <a href="https://hurna.io/academy/glossaries/index.html">https://hurna.io/academy/glossaries/index.html</a></p><p>H.urna - Opening sciences for all</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c760dc067d7" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/illustrated-guide-to-terms-used-daily-in-programming-1c760dc067d7">Illustrated guide to terms used daily in programming</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Teaching kids how to deal with integers]]></title>
            <link>https://medium.com/@urna.hybesis/teaching-kids-how-to-deal-with-integers-1a3b6fbc42b1?source=rss-131ab5a2007------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a3b6fbc42b1</guid>
            <category><![CDATA[calculus]]></category>
            <category><![CDATA[mathematics-education]]></category>
            <category><![CDATA[kids]]></category>
            <category><![CDATA[schools]]></category>
            <category><![CDATA[education]]></category>
            <dc:creator><![CDATA[Hybesis - H.urna]]></dc:creator>
            <pubDate>Tue, 14 Apr 2020 09:15:31 GMT</pubDate>
            <atom:updated>2020-04-14T09:15:31.630Z</atom:updated>
            <content:encoded><![CDATA[<p>In the previous lesson, we have learned about <a href="https://hurna.io/academy/mathematics/numbers_operations/naturals.html">natural, or whole, numbers</a> (0, 1, 2, 3…). It’s now time to enlarge our vision of numbers with integers. <strong>Integers are just like whole numbers, but they also include negative numbers: {…-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5…}.</strong> The set of integers is noted <strong>Z</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/0*x0zVfKykIq6pV26n.png" /></figure><p>In other words, the <strong>set of integers is the union of the set of natural numbers and their opposites</strong>. If <strong>a is an natural number</strong> then <strong>-a is an integer of opposite sign</strong>. On a graduated axis, <strong>two opposite numbers are symmetrical with respect to the origin (0)</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*vaD5xKLuZ07F4bEC.png" /></figure><blockquote>Please note that <strong>Zero</strong> is considered to be <strong>both positive and negative</strong>.</blockquote><blockquote>Note: Some people may have different definitions for the same word used to define a number set. Some people say that whole numbers can also be negative, which makes them exactly the same as integers. Some people also say that zero is NOT a whole number.</blockquote><blockquote>To be precise, the easiest way is to use the mathematical notation. This notation is strict and therefore avoids any confusion:<br><strong>Z </strong>: all integers.<br><strong>Z*</strong> : (Z star) all integers <strong>except 0 (zero)</strong>.<br><strong>Z+</strong> : all integers greater or equal to 0. It is the same as <strong>N</strong>.<br><strong>Z*+</strong> : all integers greater than 0. It is the same as <strong>N+</strong>.</blockquote><h3>Why using negative numbers?<br>What do they represent?</h3><p>In the 7th century AD, the Indian mathematician BRAHMAGUPTA set out for the first time rules to operate on three kinds of numbers displayed “goods”, “debts” and “zero”. Debts (somehow negative numbers) were then used in India for trade.</p><p>Today we find examples of negative numbers absolutely everywhere:<br>- <strong>Elevator</strong>: To go down into the basement we have a “-” sign telling us to go <strong>below the ground floor</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mrV_rp0gWdeNPUdY.png" /></figure><p>- <strong>Weather</strong>: If the <strong>temperature is below 0°</strong>, the “-” sign will indicate this negative temperature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oJGi6P1wiNozak8j.png" /></figure><ul><li><strong>Video game</strong>: When we <strong>lose life points</strong>, we see on the screen “-” signs in front of the numbers.<br>- <strong>Chronological frieze</strong>: A date <strong>before our year 0</strong> will be noted with a “-” sign or will be annotated “BC”.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/0*0djRc7gDgbdLPC8_.png" /></figure><p>- <strong>Finance</strong>: A bank uses positive numbers to represent deposits and <strong>negative numbers to represent withdrawals</strong>.<br>- Etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rFa3iCjiYd_orDiq.png" /></figure><p>If these negative numbers are used absolutely everywhere today, you should know that they were ignored for a very long time, or even looked down upon as difficult for the human mind to grasp. Here is a little bit of history which will also console all those who encounter difficulties with negative numbers!</p><h3>A little history</h3><p>Although the first set of rules for dealing with negative numbers was stated in the 7th century by the Indian mathematician Brahmagupta, it is surprising that in the 18th century, negative numbers were still considered absurd in Europe.</p><blockquote>In 1758, the British mathematician Francis Maseres was claiming that negative numbers “… darken the very whole doctrines of the equations and make dark of the things which are in their nature excessively obvious and simple”.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/0*OJaStHmLfmp0cUnY.png" /></figure><p>Negative numbers aren’t that easy.<br>What, exactly, do negative numbers mean?<br>How can you take 4 pens from 3?<br>How could you have less than nothing?<br>Yet today, it seems absurd to think negatives aren’t logical or useful.</p><blockquote>What happened?<br>Negatives are not something we can touch or hold.</blockquote><p>Things started to change when European scholars started translating Arabic texts obtained from North Africa. They were finally exposed to new ways of thinking, and started catching up with the Indian and Chinese subcontinent.</p><p>Rather than saying “I owe you 30″ and reading words to see if I’m up or down, I can write “-30″ and know it means I’m in the hole. The positive and negative signs automatically keep track of the direction — you don’t need a sentence to describe the impact of each transaction.</p><blockquote>With the “minus” sign notation Math became easier and more elegant. It didn’t matter if negatives were “tangible” — they had useful properties, and we used them until they became everyday items.</blockquote><p>But let’s not be smug about the struggle: negative numbers were a huge mental shift. Even Euler, the genius who discovered exponential and much more, didn’t understand negatives as we do today. They were considered “meaningless” results.</p><blockquote>As Bernard de Chartres, Isaac Newton or Blaise Pascal would say:<br>We are <strong>“Dwarfs on the shoulders of giants”</strong>.</blockquote><h3>Easily perform our operations</h3><h3>Addition &amp; Subtraction</h3><p>Good news: these operations are done exactly as for <a href="https://hurna.io/academy/mathematics/numbers_operations/naturals">natural numbers</a> !<br>Except that this time, we can go below 0; please note that <strong>‘-a’</strong> means exactly the same as <strong>‘0 - a’</strong>.</p><p>There are <strong>two unique things to know</strong> to quickly become a real ninja in the art of carrying out our operations:</p><blockquote><strong>1. Adding a negative is the same as subtracting a positive</strong>:<br><em>(−b) + a = a − b</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*voopU_YIiWViOxhPoXc9IA.png" /></figure><blockquote><em>a+(−b)=a−b</em></blockquote><blockquote><strong>2. Subtracting a negative is the same as adding a positive</strong>:</blockquote><blockquote><em>a−(−b)=a+b</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*OvofuqAZjjaqVG5zuBFzJg.png" /></figure><p>Let’s take an example that looks complicated and turn it into something very simple:<br>5 + 4 − 3 + (−2) −2 − (−4) = ?</p><p>Rule 1 : +(-2) →- 2<br>Rule 2 : -(-4) → + 4</p><p>Thus:<br>… = 5 + 4 − 3 − 2 − 2 + 4 = 65</p><blockquote>And voila! <br>We already know everything about addition and subtraction!</blockquote><h3>Multiplication &amp; Division</h3><blockquote>We still have good news!</blockquote><p>As for additions and subtractions:<br>- These operations are done exactly as for <a href="https://hurna.io/academy/mathematics/numbers_operations/naturals">natural numbers</a><br>- There are two unique things to know.<br>- The combination of signs results the same.</p><blockquote><strong>1. The product of two numbers of opposite sign is negative</strong>:<br><em>−b ∗ a = −(a∗b)</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*voopU_YIiWViOxhPoXc9IA.png" /></figure><blockquote><em>a ∗ −b = −(a∗b)</em></blockquote><blockquote><strong>2.The product of two numbers of the same sign is positive</strong>:<br><em>(−a) ∗ (−b) = a∗b</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*OvofuqAZjjaqVG5zuBFzJg.png" /></figure><p>Here are some very simple examples to illustrate:<br>a. −3 ∗ −3 = 9<br>b. 2 ∗ −3 = −6<br>c. 2 ∗ 2 = 4<br>d. −3 ∗ 6 = −18</p><p>e.−3 ∗ 3 ∗ −3 <br> = −9 ∗−3<br>=27</p><p>f. −2 ∗ 2 ∗ −2 ∗ 2 ∗ −2 <br> =−4 ∗−4 ∗ −2<br> = 16 ∗ −2 <br> = −32</p><blockquote><strong>And finally, a mnemonic often used, a friend is ‘+’, an enemy is ‘-’:<br></strong>+ + ⇒ + | a friend of a friend is my friend<br>+ − ⇒ − | a friend of an enemy is my enemy<br>− + ⇒ − | an enemy of a friend is my enemy<br>− − ⇒ + | an enemy of an enemy is my friend</blockquote><p>Be the math with your Kids!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a3b6fbc42b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Teaching kids how to operate natural numbers]]></title>
            <link>https://medium.com/@urna.hybesis/teaching-kids-how-to-operate-natural-numbers-abee28fc45ae?source=rss-131ab5a2007------2</link>
            <guid isPermaLink="false">https://medium.com/p/abee28fc45ae</guid>
            <category><![CDATA[education]]></category>
            <category><![CDATA[numbers]]></category>
            <category><![CDATA[math]]></category>
            <category><![CDATA[schools]]></category>
            <category><![CDATA[kids]]></category>
            <dc:creator><![CDATA[Hybesis - H.urna]]></dc:creator>
            <pubDate>Tue, 14 Apr 2020 08:53:40 GMT</pubDate>
            <atom:updated>2020-04-24T11:12:34.046Z</atom:updated>
            <content:encoded><![CDATA[<p>A natural number is a <strong>positive and “without comma” number such as 1, 2, 3 … and 0</strong>. <strong>The smallest element is 0 and there is no greater element</strong>: you can count without ever stopping.</p><p>Natural numbers are <strong>the most commonly used numbers in everyday life</strong>, they allow you to count a distinct number of objects (or units). For example, we can have 2 pens, 1 cat and a bill of 5 dollars in our pocket etc.</p><p>The set of natural whole numbers is noted N, it is a tiny part (even if it is infinite) of existing numbers. It is for example a set smaller than the one of the integers Z.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/0*cOW8c_wSByRGWv2S.png" /></figure><blockquote>The theory stops there! We will now get to the heart of the matter. We will first see how to write whole numbers, then what mathematical operations mean and how to perform them.</blockquote><h3>Decomposing a Number — Number Units</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*jBPgFuY02QrxsiOVAdcXbA.png" /></figure><p>Given an integer, the <strong>rightmost digit is the units digit</strong>, which is written in the units column. The one <strong>immediately to the left is the tens digit</strong>, which is written in the tens column. We complete the table so on from right to left, until all the numbers are written.</p><blockquote>Note: The more a digit is located to the left of the number, the greater its value. For example, 6 hundreds is greater than 6 tens because the hundreds are more to the left than the tens.</blockquote><h3>Perform a mathematical operation</h3><h3>Addition</h3><p>Performing <strong>an addition is adding quantities</strong>, we call it: <strong>calculating the sum of several terms (or numbers)</strong>. For instance, let’s count the steps we take forward: if we take one step and then two steps, we will have made 1 + 2 = 3 steps forward in total. Below is the table of the additions of the figures from 1 to 10:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/0*s5ByH7xgb3GtCeVx.png" /></figure><p>The good news is that <strong>we don’t need to remember these kind of tables</strong> and that we will be able to use our blank numbering table to make all kind of additions. We put the numbers one below the other with aligning the figures (number units) in a column, then we add the numbers, column by column, from the right to the left.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*u3tPs9Zr-LIvTvpudz3d6A.png" /></figure><blockquote><strong>Please note: we must not forget to carry over the retain when the sum of the digits is greater than 10 (as shown in our example on the right).</strong></blockquote><blockquote>In the calculation of a sum, the order of the terms does not matter (the operation is said to be commutative): <em>2+4 = 4+2 = 6</em></blockquote><blockquote>In the calculation of a sum, we can group terms to facilitate the calculation (the operation is called associative): <em>8 + 2 + 8 + 2 = (8+2) + (8+2) = 20</em></blockquote><h3>Subtraction</h3><p>The <strong>subtraction</strong> is an operation that calculates <strong>the difference between two (or more) numbers</strong>. This <strong>difference between 2 numbers is the number that must be added to one to get the other</strong>.<br>Let’s say I have 1 pen in my kit, how many more do I need to have 3?</p><p>The answer is : 3 - 1 = 2.<br>I need 2 more pens to have 3 pens in the end.</p><p><strong>Another way of looking at subtraction is to remove quantities.</strong> For example by going down steps: if we climb 3 steps and then go down a 1 step, we will have climbed 3 - 1 = 2, that is 2 steps in total.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*Jl_HCf6-1MLszrIk.png" /></figure><p>To subtract two numbers, the terms are laid out in the same way as for an addition, then we subtract the numbers, column by column, from the right. <strong>If the number above is less than the number below, we add 10 to the number at the top, then we transfer the retain (-1) to the left column.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*fvkgqgWDWYsbQXwrOvaHNw.png" /></figure><blockquote>In the first example, we see in the tens column that 4 is less than 5. We will then have (4 + 10) - 5 = 14 - 5 = 9. Then we carry the retain -1 on the left column.</blockquote><h3>Verification</h3><p>If we have a little doubt about our result, the calculation of the verification allows us to quickly check it. We simply check that our result + the term subtracted = the first number. With the two operations carried out above, we will therefore have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*BbPmjiP4lRVSjGkPtcJj2w.png" /></figure><blockquote>Perfect, we fall back on our initial numbers: the calculations are verified!</blockquote><h3>Subtract a larger number?</h3><blockquote>In the natural numbers set, <strong>this operation is impossible!</strong><br><strong>The operation is not stable</strong> in this set.<br>But don’t panic because the next lesson, the one about <a href="https://hurna.io/academy/mathematics/numbers_operations/integers.html"><strong>integers, explains how to overcome this problem ;)</strong></a></blockquote><h3>Multiplication</h3><p>The <strong>multiplication</strong> is an operation which allows <strong>to calculate the product</strong> between two numbers. <strong>Multiplication corresponds to an addition repeated several times.</strong> It makes it possible to greatly simplify the writings as well as the calculations.</p><p>Let’s take “<strong>3 + 3 + 3 + 3 + 3 + 3 + 3 + 3 + 3 + 3 + 3</strong>” (11 in total), this calculation can be written <strong>11 * 3</strong>. We will also say that we have 11 times the number 3, for a total of 33. Below is the multiplication table for the numbers from 1 to 10:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/0*U_VvfMcdnQ6kwhwS.png" /></figure><blockquote>When we multiply by 10, we simply shift each digit in the box to the left. For example 20 x 10 = 200 (the 2 of tens became the 2 of hundreds).</blockquote><p>We are now used to it (it’s always the same technique), we start by arranging the numbers one below the other by aligning the numbers in columns (numbering units), then we multiply the numbers, column by column, from the right.</p><blockquote><strong>Warning!!!<br>When the multiplier is a number made up of several digits, the calculations are carried out digit after digit with all of the digits of the top number.<br>Then, for the next digit of the multiplier (bottom):<br>We go to the line and we shift the results of a column (see the example on the right).</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*tIStK5R_Dbrr_1pbR7NqoA.png" /></figure><blockquote>Please note: We must not forget to defer the retain when the product of the figures is greater than 10 (this retain must be added).</blockquote><blockquote>In the calculation of a product, the order of the terms does not matter (the operation is said to be commutative): 2 * 4 = 4 * 2 = 8</blockquote><blockquote>In the calculation of a product, we can group terms to facilitate the calculation (the operation is called associative): 3 * 2 * 3 * 2 = (3 * 3) * (2 * 2) = 36</blockquote><blockquote><strong>Congratulations, we have just obtained the most fundamental bases in mathematics !!<br>May the math be with us!</strong></blockquote><h3>Division</h3><p>Now that we have learned how to multiply integers, dividing should be a breeze. The reason is that they follow the same rules. <strong>The division allows us to calculate the sharing problems, it is the opposite of multiplying.</strong></p><blockquote>Example:<br>There are 12 blue candies, and 4 friends want to share them, how do we divide the candies?</blockquote><p>The answer may seem evident: if each friend takes 3 candies, we are all good. <strong>Division is splitting into equal parts or groups. It is the result of “fair sharing”.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7z78DyQtHDH32q4D.png" /></figure><p>Note:<br>As we said, another way to <strong>think of division is as the opposite of multiplication</strong>. Taking this example we got:</p><p>→ 12 / 4 = 3 (we gives 3 candies to each of us)</p><p>Now if we invert the operation using the result, we replace the ‘=’ with a ‘x’ sign and the ‘/’ with an ‘=’ sign:</p><p>→ 12 = 3 x 4 (if 3 candies are given to each of us, we shared a total of 12 candies)</p><blockquote>This is, indeed, the mathematical definition of the division:<br><em>a / b = a ∗ (1 / b)</em></blockquote><blockquote>Using multiplication is a great way to check our division and master our math tests. But remember this rule, it is the only one to know when dealing with division:<br><strong>We never divide by 0!</strong></blockquote><h3>But… Sometimes it does not fit perfectly!</h3><blockquote>Indeed, sometimes, we have a remainder; we will address this case and more complex ones within a dedicated course: “The Euclidean division” ;)</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abee28fc45ae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A quick introduction to number sets and math vocabulary]]></title>
            <link>https://medium.com/@urna.hybesis/a-quick-introduction-to-number-sets-and-math-vocabulary-719794796e90?source=rss-131ab5a2007------2</link>
            <guid isPermaLink="false">https://medium.com/p/719794796e90</guid>
            <category><![CDATA[calculus]]></category>
            <category><![CDATA[operations]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[rules]]></category>
            <category><![CDATA[numbers]]></category>
            <dc:creator><![CDATA[Hybesis - H.urna]]></dc:creator>
            <pubDate>Sun, 12 Apr 2020 08:33:56 GMT</pubDate>
            <atom:updated>2020-04-12T08:33:56.497Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In this introduction we will see the vocabulary and the calculation rules used for all the set of numbers. This may seem complicated at first, but for each set (see Quick Access above) we will explain in detail and with examples how to do it. <strong>This general vision will then become super practical to quickly consult all the rules, the vocabulary and what each set represents.</strong></p><p>Let’s start with the big picture, how are the first sets of numbers categorized?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*z8LiIJWIjrdy0dAb.png" /></figure><p><strong>N</strong> : A natural integer is a <strong>positive and “without comma” number such as 0, 1, 2, 3 …</strong></p><p><strong>Z</strong> : An integer is either a <strong>positive or negative number and “without comma” such as<br> …-3, -2, -1, 0, 1, 2, 3…</strong></p><p><strong>Q</strong> : A rational number is a <strong>number which can be written as a fraction such as 1/3, -2/7 etc.</strong></p><p><strong>R</strong> : <strong>Some numbers like √2 or π are not rational.</strong> The set of reals completes the set Q.</p><h3>Priorities (order) of operations</h3><blockquote>Like the rules (below), the operational priorities are true all the time. We will have to follow them each time we have a calculation to perform :</blockquote><p><strong>1.</strong> Calculations in <strong>parentheses</strong><br><strong>2.</strong> <strong>Powers</strong><br><strong>3.</strong> <strong>Multiplication and Division</strong><br><strong>4.</strong> <strong>addition and subtraction</strong><br><strong>5.</strong> In case of operations with the same priorities, it is at our convenience (we do as we want).</p><h3>Some examples</h3><p>4×3+6 = 12+6 = 18</p><p>3×5−2×3+5 = 15−6+5 = 14</p><p>(5−3)×(7+1) = 2∗8 = 16</p><h3>Calculation rules and vocabulary</h3><blockquote>This vocabulary and these calculation rules will follow you until the end of your studies and will remain unchanged. It may seem a little heavy at first, but we will use it daily in math whatever the level of study. Let’s go:</blockquote><h3>Division</h3><blockquote><strong>We never divide by 0 !</strong></blockquote><h3>Neutral element</h3><p>we call <strong>neutral element</strong> a number that <strong>does not change the result of an operation</strong>.</p><blockquote><strong>The addition</strong> has a neutral element, <strong>the null element: a + 0 = a</strong><br><strong>The multiplication</strong> has a neutral element, <strong>the unit : a × 1 = a</strong></blockquote><h3>Inverse number</h3><p>We call <strong>inverse of the number</strong> a (not zero) the number noted <strong>a-1 or 1/a that verifies :</strong></p><p>a ∗ 1/a = 1</p><p>or</p><p>a ∗ a^(−1) = 1</p><h3>Opposite number</h3><p>We call <strong>opposite of the number</strong> a the number noted <strong>–a that verifies :</strong></p><p>a +(−a) = 0</p><p>On a graduated axis, two opposite numbers are symmetrical with respect to the origin (0).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*vbXAoMu10Re-iHW0.png" /></figure><h3>Associative operation</h3><p>An operation is <strong>associative</strong> if the result is invariable whatever the grouping of consecutive terms. In other words if the <strong>operator (noted ❄︎) </strong>has the following properties regardless of the elements a, b and c:</p><p>(a❄︎b)❄︎c = a❄︎(b❄︎c)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_UDNdkj4lHPwir2D.png" /></figure><blockquote><strong>The addition</strong> is associative : <strong>(a + b) + c = a + (b + c)</strong><br><strong>The multiplication</strong> is associative : <strong>(a × b) × c = a × (b × c)</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4NNxzEopkddN9mKN.png" /></figure><blockquote><strong>Attention: Subtraction and division are not associative!</strong></blockquote><h3>Commutative operation</h3><p>A <strong>commutative operation </strong>is an operation which allows <strong>to change the order of terms without changing the result</strong>.</p><blockquote><strong>The addition</strong> is commutative : <strong>a + b = b + a</strong><br><strong>The multiplication</strong> is commutative : <strong>a × b = b × a</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KwQHpMsozXNVOUX6.png" /></figure><p>Mathematically, this would be written:</p><p>∀x,y∈R:x+y=y+x</p><p>∀x,y∈R:x×y=y×x</p><blockquote><strong>Attention: Subtraction and division are not commutative!</strong></blockquote><h3>Distributive operation</h3><p><strong>Multiplication is distributive on addition.</strong> This translates as follows:</p><p>a∗(b+c)=(a∗b)+(a∗c)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/0*nQ6XNZyYEWmCeLLr.png" /></figure><blockquote>The image above is a visual demonstration. Indeed, we can see that the area of the total rectangle “c * (a + b)” is equal to the sum of the two interior areas “(c * a) + (c * b)”.</blockquote><h3>Stable operation</h3><p>In mathematics, we say that a part A of a set E is stable (or closed) for an operation defined on E if this operation, applied to elements of A, produces an element of A.</p><blockquote>For example, the set N (natural integers or positive integers) is stable for addition and multiplication: this means that if I add or multiply any two natural integers, the result will still be a natural integer.</blockquote><blockquote>N is not stable for subtraction (or division): for example 2–3 = -1, which is not in N.</blockquote><blockquote>Voilà ! We now know the rules of the game for performing mathematical calculations.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=719794796e90" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Binary Search Tree — BST]]></title>
            <link>https://levelup.gitconnected.com/mastering-binary-search-tree-bst-e860c1e3ac39?source=rss-131ab5a2007------2</link>
            <guid isPermaLink="false">https://medium.com/p/e860c1e3ac39</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[bts]]></category>
            <category><![CDATA[recursion]]></category>
            <category><![CDATA[complexity]]></category>
            <category><![CDATA[binary-search-tree]]></category>
            <dc:creator><![CDATA[Hybesis - H.urna]]></dc:creator>
            <pubDate>Fri, 21 Feb 2020 13:34:28 GMT</pubDate>
            <atom:updated>2020-07-26T21:56:08.888Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mastering Binary Search Tree — BST</h3><h3>Introduction</h3><p><strong>A Binary Search Tree (BST), Ordered Tree or Sorted Binary</strong> is the first tree data structure we are studying. Unlike <a href="https://hurna.io/academy/data_structures/array.html">Arrays</a>, <a href="https://hurna.io/academy/data_structures/linked_list.html">Linked Lists</a>, <a href="https://hurna.io/academy/data_structures/stack.html">Stacks</a> and <a href="https://hurna.io/academy/data_structures/queue.html">Queues</a> which are linear data structures, a Tree <strong>is a hierarchical (and nonlinear) data structure which is intrinsically recursive</strong>. Still, BST are easy to understand and manipulate. Here is how it looks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*kv3gVgJV67WCl9po.png" /></figure><p>One reason to use trees might be because we want to store information that naturally forms a hierarchy. Another one is their very important characteristic that <strong>allows fast — O(log n) — insert, search and delete operations</strong>.</p><h3>Tree, Binary Trees and Binary Search Trees (BST)</h3><blockquote>Before tackling BST it is important to precise the terminologies, which are often confused.</blockquote><h4>Tree</h4><p><strong>A tree has no restrictions on the number of children</strong> each node can have. <strong>The topmost node</strong> in a tree is called <strong>the root node</strong> and the <strong>nodes with no children are called leaf nodes</strong>. They are also called N-ary trees:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/0*38bSOYtCQ9pg0AhM.png" /></figure><blockquote>The height of a tree is the number of edges from the root to the deepest leaf (here height = 3).</blockquote><h4>Binary Tree</h4><p>Binary trees is a general concept of particular tree-based data structure. Various specific types of binary trees (e.g. BST below) can be constructed with different properties based on this concept. <strong>Binary trees can have at most two children</strong> for each node. Every node in a binary tree contains:<br>- A <strong>data element</strong> (e.g. 6)<br>- A <strong>pointer to the ‘left child’ node</strong> (may be ‘null’)<br>- A <strong>pointer to the ‘right child’ node</strong> (may be ‘null’)</p><blockquote>It may sound surprising, but the organization of the Morse code is a binary tree.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*71buNWSIZhQmoqkx.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*khPasrSniIHeXuEt.png" /></figure><h3>Some other applications of binary trees</h3><ul><li>Use to structure mathematical expressions within a calculator (Syntax Tree). This is for instance what is used by our <a href="https://demo.hurna.io/#path=equation_solver/quadratic">AI Globo to solve your quadratic equations step-by-step</a>.</li><li>Constructed by compilers to parse expressions as calculators (Syntax Tree)</li><li>Used in almost every 3D video game to determine what objects need to be rendered (Binary Space Partition).</li><li>Use in compression algorithms such as mp3, jpg (Huffman Coding Tree)…</li></ul><h4>Binary Search Tree — BST</h4><p>Finally comes our <strong>BST</strong>, which is a binary tree data structure with the two following constraints:<br>- <strong>All nodes of the left subtree</strong> of a node have a value <strong>less than or equal to the node’s</strong> value.<br>- <strong>All nodes of the right subtree</strong> of a node has a value <strong>greater to its parent’s</strong> value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*z_UUluXMjIbYgCi7.png" /></figure><blockquote>The binary tree on the right isn’t a binary search tree because the right subtree of the node “3” contains a value smaller than it.</blockquote><p>Advantages / Drawbacks</p><ul><li><strong>+ Use the principle of binary search for insert, delete and lookup operations which have an O(log n) complexity.</strong></li><li>+ Get all keys in sorted order by just doing a inorder traversal.</li><li>+ Doing order statistics, closest lower/greater elements, range queries etc. operations are easy.</li><li>+ Trees are very flexible data, allowing to move subtrees around with minimum effort.</li><li>- The shape of the binary search tree depends on the order of insertions and deletions, and <strong>may become very unbalanced</strong> (if not managed — more detailed further). If the tree is completely degenerate, we finish up with something similar to a linear data structure : a linked list.</li></ul><h3>Let’s have a break with some peaceful binary tree fractals</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*rQ04d_TWwMf7X-OT.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*c-92q9HtBxhtwCIe.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hJFyH_u-DI42KA13.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FBxL2P55hGL3TEQd.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zthzUN_ppUqPx6xJ.png" /></figure><h3>Objectives</h3><blockquote>Operate a BST.<br>Build our own BST structures.<br>Put into practice pointers and recursion.<br>Understand the advantages / disadvantages of balancing a tree.</blockquote><h3>What is next?</h3><p>If you haven’t jumped yet to <a href="https://hurna.io/academy/maze_generator/index.html">maze generation algorithms</a>, playing with them and using our <a href="https://demo.hurna.io/#path=maze/binary_generator">explorer</a> gives you visual insights of the duality between a maze and a tree structure. We will soon study more advanced tree structures such as red-black tree or, quadtrees and octrees which are two very useful structures to partition 2D and 3D spaces.</p><h3>Build our own</h3><p>We will first simply define our structure with Binary Trees that contains a data, a pointer to the left subtree (node), a pointer to the right subtree (node). The code is simplified for reading purpose, please use <a href="https://github.com/Hurna/Hurna-Core/blob/master/Modules/DataStructures/binary_search_tree.hxx">the github link</a> to get access to the full version.</p><pre>class BST<br>  {<br>    BST(const Value data) : data(data) {}<br>    ...<br><br>  private:<br>    T data;<br>    unique_ptr&lt; BST &gt; leftChild;<br>    unique_ptr&lt; BST &gt; rightChild;<br>  }</pre><blockquote>The semantic of the code shows that recursion plays a major role in tree data structures. Indeed, the left and right nodes of a BST are subtrees also defined as BST.</blockquote><p>Binary search trees support everything you can get from a sorted array: efficient search, in-order forward/backwards traversal from any given element, predecessor/successor element search, and max/min queries…</p><blockquote>Why not using a simple sorted array and use binary search then?</blockquote><p>Having a sorted array is useful for many tasks because it enables <a href="https://hurna.io/academy/algorithms/search/binary.html">binary search</a> to be used to efficiently locate elements : O(log n). The problem with a sorted array is that elements can’t be inserted and removed efficiently in comparison with binary search trees.</p><blockquote>Great. Since we have good reasons to proceed, let’s define an API.</blockquote><pre>// Manipulation<br>  void Insert(Value data)     // Insert an element<br>  BST* Remove(Value data)     // Remove an element</pre><pre>  // Traversal<br>  Value GetMin()              // Return the minima<br>  Value GetMax()              // Return the maxima<br>  List&lt; Value &gt; InOrder()     // Proceed in order traversal <br>  BST* Search(Value data)     // Find an element</pre><p>That’s a pretty big API, we will take it one section at a time to master tree operations. We will tackle them from the traversal methods to the manipulative ones.</p><h3>Traversals</h3><h3>GetMin / GetMax</h3><p>They are the easiest methods and they allow us to remember the properties of a BST:<br>- <strong>All nodes of the left subtree</strong> of a node have a value <strong>less than or equal to the node’s</strong> value.<br>- <strong>All nodes of the right subtree</strong> of a node has a value <strong>greater to its parent’s</strong> value.</p><pre>// GetMin is getting the left most child<br>  const BST* GetMin()<br>  {<br>    auto curNode = this;<br>    while (curNode-&gt;leftChild)<br>      curNode = curNode-&gt;leftChild;</pre><pre>    return curNode;<br>  }</pre><pre>  // GetMax is getting the right most child<br>  const BST* GetMax()<br>  {<br>    auto curNode = this;<br>    while (curNode-&gt;rightChild)<br>      curNode = curNode-&gt;rightChild;</pre><pre>    return curNode;<br>  }</pre><p>See below the recursive version for illustration (more memory consumption).</p><pre>const BST* GetMin() <br>{ return this-&gt;leftChild ? this-&gt;leftChild-&gt;GetMin() : this; }</pre><pre>const BST* GetMax() <br>{ return this-&gt;rightChild ? this-&gt;rightChild-&gt;GetMax() : this; }</pre><h3>Search</h3><p>Searching for a value uses the same principle as the <a href="https://hurna.io/academy/algorithms/search/binary.html">Binary Search in a sorted array</a>. If the <strong>value is lesser</strong> than the current node, we can say for sure that the value is in the <strong>left subtree</strong>, <strong>otherwise</strong> it is in <strong>the right one</strong>.</p><h3>Inorder traversal</h3><p>In an inorder traversal, we <strong>first visit the left child</strong> (including its entire subtree), <strong>then visit the current node</strong> and <strong>finally visit the right child</strong> (including its entire subtree). Note that the binary search tree makes use of the inorder traversal method to get <strong>all nodes in ascending order</strong> of value.</p><pre>static void Inorder(const BST* node, List&lt; Value &gt;&amp; result)<br>  {<br>    if (!node) return; // end of a branch (no data)</pre><pre>    Inorder(node-&gt;leftChild)  // Recurse in left subtree<br>    result.push(node-&gt;data);  // Get data<br>    Inorder(node-&gt;rightChild) // Recurse in right subtree<br>  }</pre><h3>Manipulate</h3><h3>Insert</h3><p><strong>Inserting a value in the correct position is similar to searching</strong> because we want to maintain the rule that left subtree is lesser than root and right subtree is larger than root. We keep going to either right or left depending on the value until we are a leaf. Then, we put the new node (or BST) there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*IVZ6lXqcqX56hSh_ru7GdQ.png" /></figure><p>We may have noticed that the order of insertion may change the shape of our BST. This is the drawback mentioned earlier : our tree can be very unbalanced (or degenerate).</p><blockquote>Left: we insert in order [4,2,5,1,3,6] → O(log n)<br>Right: we insert in order [1,2,3,4,5,6] → O(n)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*aTW2azy5GyT9xxNv.png" /></figure><p>We can see that the <strong>running times of algorithms on binary search trees depend on the shapes of the trees</strong>, which, in turn, depends on the order in which keys are inserted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WEIGkEtQndEvPVwHAh4aSA.png" /></figure><blockquote>There are techniques known as tree balancing which maintain the tree balanced. We will see them with more advanced tree data structures such as red-black trees.</blockquote><blockquote>However, it is reasonable for many applications to use a BST if we assume that data are inserted in a random order. In that case, our operations with n nodes requires about 2 ln n.</blockquote><blockquote>As a first exercise we may write the procedure that will produce a balanced BST from a sorted array.</blockquote><h3>Remove</h3><p>The last operation in the BST that we are going to discuss in depth is removing a node based on a given value. Deletion is somewhat more tricky than insertion as there are three cases to consider if the node exists in the tree:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*TR5FkZ5UuH00l47cJrHnmw.png" /></figure><blockquote>Voila ! We now master BST and its operations, which give us a solid foundation daily used in software development.</blockquote><h3>Some exercises</h3><pre>bool IsBalanced()   // Check if the tree is balanced<br>int MinHeight()     // Return the smallest branch height<br>int MaxHeight()     // Return the highest branch height<br>int Size()          // Return number of nodes composing the tree</pre><p>Stay connected for more advanced courses.</p><p><a href="https://hurna.io/">H.urna — Science for everyone.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e860c1e3ac39" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/mastering-binary-search-tree-bst-e860c1e3ac39">Mastering Binary Search Tree — BST</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pathfinding algorithms : the four Pillars.]]></title>
            <link>https://levelup.gitconnected.com/pathfinding-algorithms-the-four-pillars-1ebad85d4c6b?source=rss-131ab5a2007------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ebad85d4c6b</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[pathfinder]]></category>
            <category><![CDATA[visualization]]></category>
            <category><![CDATA[graph]]></category>
            <category><![CDATA[maze]]></category>
            <dc:creator><![CDATA[Hybesis - H.urna]]></dc:creator>
            <pubDate>Mon, 20 Jan 2020 19:02:38 GMT</pubDate>
            <atom:updated>2020-01-20T19:02:38.572Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Pathfinding algorithms : the four Pillars.</strong></h3><h3>Introduction</h3><blockquote>What’s the shortest drive from our place to the nearest park?<br>How do we find a way through a maze?<br>Can we program a game character to find the exit avoiding enemies?</blockquote><p>Pathfinding algorithms address the problem of <strong>finding a path from a source to a destination avoiding obstacles and minimizing the costs </strong>(time, distance, risks, fuel, price, etc.). This is a common programming challenge. Mainly known from navigation and games, we will find that the core algorithms apply to a huge range of problems.</p><p>For a brief introduction about mazes and why we enjoy them so much, please refer to ‘<a href="https://hurna.io/academy/algorithms/maze_generator/index.html">Introduction to Maze Generators</a>’.</p><h3>Objectives</h3><p>We will first study <a href="https://hurna.io/academy/algorithms/maze_pathfinder/bfs.html">Breadth First Search</a> and <a href="https://hurna.io/academy/algorithms/maze_pathfinder/dfs.html">Depth First Search</a> because they are fundamental for traversing a graph (or a tree) and are often a required first step for many other types of analysis. We will then cover more advanced algorithms such as <a href="https://hurna.io/academy/algorithms/maze_pathfinder/dijkstra.html">Dijkstra</a> or <a href="https://hurna.io/academy/algorithms/maze_pathfinder/a_star.html">A* (A-Star)</a>.</p><h3>Understanding the data</h3><blockquote>The first thing to do when studying an algorithm is to understand the data.<br>What is the input? What is the output?<br>Here is the kind of board we will play with.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NbEqlPSrS_w5w51H.png" /></figure><blockquote>How is the data structured?<br>Here is a labyrinth with a few more details.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/0*l9z1NnR483wceS6L.png" /></figure><p>In this grid, each box represents a node. A connection between two nodes is represented by a path between two boxes. This information is also displayed textually (top left box in the image). Here, our mouse is on the first node (0,0) and displays connections with the nodes (0,1) and (1,0).</p><p>We choose to describe our grid (or graph) using an <strong>adjacency lists</strong> data structure. The idea is pretty simple : <strong>an array of nodes with node storing the list of their neighbors</strong>. Easy to create, easy to manipulate, here is how the data could be represented in JSON :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*EUxv9r13eKYFDQppY3Vxnw.png" /></figure><p>The node id is given by its array index, this id is used to refer to the neighbors.<br>Yes, it’s that simple! It includes all the information we need to go through and to visualize the maze.</p><blockquote>What is the output?</blockquote><p>The most basic output that could be expected is the path found between two nodes. To represent this, an ordered (by step order) array is quite sufficient:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*gmVmZYT7SFzUZFL-BnB91A.png" /></figure><p>Starting from the node 0, we go to node 3, then to node 19 etc. until the goal.</p><blockquote>Perfect, we know everything to build our pathfinders!</blockquote><blockquote>Note: A grid can use a non-grid pathfinding graph, or vice versa.<br>Here, grids are used for explanations as it is easier to understand, work and visualize.</blockquote><h3>Overview</h3><h3><a href="https://hurna.io/academy/algorithms/maze_pathfinder/bfs.html">Breadth First Search</a></h3><blockquote>Breadth First Search explores equally in all directions.</blockquote><blockquote>This is an incredibly useful algorithm, not only for regular traversal, but also for procedural map generation, flow field pathfinding, distance maps, and other types of map analysis.</blockquote><blockquote>This may be the algorithm of choice to identify nearby places of interest in GPS.</blockquote><blockquote>BFS guarantees the shortest path.</blockquote><h3><a href="https://hurna.io/academy/algorithms/maze_pathfinder/dfs.html">Depth First Search</a></h3><blockquote>Traverses by exploring as far as possible down each path before backtracking.</blockquote><blockquote>As useful as the BFS: DFS can be used to generate a topological ordering, to <a href="https://hurna.io/academy/algorithms/maze_generator/dfs.html">generate mazes</a>, to traverse trees, to build decision trees, to discover a solution path with hierarchical choices…</blockquote><blockquote>DFS does not guarantee the shortest path.</blockquote><h3><a href="https://hurna.io/academy/algorithms/maze_pathfinder/dijkstra.html">Dijkstra</a></h3><blockquote>Dijkstra’s Algorithm lets us prioritize which paths to explore. Instead of exploring all possible paths equally, it favors lower cost paths.</blockquote><blockquote>We can assign lower cost to encourage moving on roads while assigning high cost on highway to avoid them.</blockquote><blockquote>It is the algorithm of choice for finding the shortest path paths with multiple destinations.</blockquote><h3><a href="https://hurna.io/academy/algorithms/maze_pathfinder/a_star.html">A* (A-Star)</a></h3><blockquote>A* is a modification of Dijkstra’s Algorithm that is optimized for a single destination.</blockquote><blockquote>Dijkstra’s Algorithm can find paths to all locations; A* finds paths to one location. It prioritizes paths that seem to be leading closer to a goal.</blockquote><blockquote>In a game, we could set costs to be attracted or discouraged in going near some objects : how useful it is for an AI.</blockquote><blockquote>It is more or less the <strong>golden ticket</strong> or <strong>industry standard</strong> algorithm for all applications finding directions between two locations.</blockquote><h3>Breadth First Search (BFS)</h3><p><strong>Breadth First Search (BFS) is one of the two most fundamental graph traversal algorithms.</strong> First published in 1959 by Edward F. Moore to find the shortest path out of a maze, it is now used in a daily basis not only for regular traversal, but also for networks analysis, GPS, Search Engines, scheduling and other types of graph analysis.</p><blockquote>In short : this is an incredibly useful algorithm that guarantees the shortest path between two nodes (when connections have the same cost).</blockquote><p>Breadth First Search explores equally in all directions until the goal is reached. In other words, it <strong>starts from a chosen node and examine all its neighbors, then it examines all the neighbors of the neighbors, and so on… </strong>If we consider a tree (which is a simplified graph), the BFS will proceed as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*b31hiO4ynbDLRrXWEFF4aQ.png" /></figure><h3>How To Build</h3><h3>Steps</h3><ul><li>Add the start node in the queue and mark as visited.</li><li>While there is a node waiting in the queue:</li><li>1. <strong>Take the node</strong> at the front of the line (queue).</li><li>2. <strong>Add to the queue all available neighbors, note the parent and mark as visited</strong></li><li>Done: backtrack from goal to start using parent link in order to get the shortest path.</li></ul><blockquote>BFS uses the opposite strategy as <a href="https://hurna.io/academy/algorithms/maze_pathfinder/dfs.html">depth-first search (DFS)</a>, which instead explores the node branch as far as possible before being forced to backtrack. Still, both algorithms have the same lines of code; the only difference is the data structure used:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/0*K_h_2m79W_NDjEKP.png" /></figure><p>BFS use a <a href="https://hurna.io/academy/data_structures/queue.html">Queue (FIFO)</a></p><p>This algorithm is, compared to the DFS, a little more tricky to implement in a recursive manner. As such we will only see the iterative approach ;)</p><h3>Code</h3><pre>BFS(Maze maze, Node start, Node end)<br>{<br>  // Put the start node in the queue<br>  start.visite = true;<br>  Queue queue(start);</pre><pre>  // While there is node to be handled in the queue<br>  while (!queue.empty())<br>  {<br>    // Handle the node in the front of the line <br>    Node curNode = queue.pop();</pre><pre>    // Terminate if the goal is reached<br>    if (curNode == end)<br>      break;</pre><pre>    // Handle neighbors<br>    auto neighbors = curNode.GetUnvisitedNeighbors();<br>    for (auto i = 0; i &lt; neighbors.size(); ++i)<br>    {<br>      neighbors[i].visite = true;<br>      neighbors[i].parent = curNode;<br>      queue.push(neighbors[i]);<br>    }<br>  }</pre><pre>  // Done ! At this point we just have to walk back from the end using the parent<br>  // If end does not have a parent, it means that it has not been found.<br>}</pre><h3>Visualization</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fvf817b882Uw%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dvf817b882Uw&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fvf817b882Uw%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce5db5c349d0e22ab7f2ca30e5023954/href">https://medium.com/media/ce5db5c349d0e22ab7f2ca30e5023954/href</a></iframe><h3><strong>Depth First Search (DFS)</strong></h3><p><strong>Depth First Search (DFS) is the other fundamental graph traversal algorithm; </strong><a href="https://hurna.io/academy/algorithms/maze_pathfinder/bfs.html">Breadth First Search (BFS) is the other one</a>. As useful as the BFS, the DFS can be used to generate a topological ordering, to generate mazes (cf. <a href="https://hurna.io/academy/algorithms/maze_generator/dfs.html">DFS maze generators</a>), to traverse trees in specific order, to build decision trees, to discover a solution path with hierarchical choices, to detect a cycle in a graph…</p><blockquote>However, please first note that the DFS does not guarantee the shortest path.<br>Then, this is not a very good algorithm if the unique purpose is to do a simple pathfinding.</blockquote><p>Depth First Search Traverses by exploring as far as possible down each path before going back. It is the reason why you may also find this algorithm under the name of <strong>Backtracking</strong>. Furthermore, This property allows the algorithm to be implemented succinctly in both iterative and recursive forms. If we consider a tree (which is a simplified graph), the DFS will proceed as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*2XxSVULNUNVKwLM0.png" /></figure><h3>How To Build</h3><h3>Steps</h3><ul><li>Add the start node in the stack and mark as visited.</li><li>While there is a node waiting in the stack:</li><li>1. <strong>Take the node</strong> at the top of the stack.</li><li>2. <strong>Add on the stack all available neighbors in order, note the parent and mark as visited</strong><br>(we chose for the visualization North, East, South, West as order)</li><li>Done: backtrack from goal to start using parent link in order to get the path.</li></ul><blockquote>DFS uses the opposite strategy as <a href="https://hurna.io/academy/algorithms/maze_pathfinder/bfs.html">breadth-first search (BFS)</a>, which instead explores the node circle by circle. Still, both algorithms have the same lines of code; the only difference is the data structure used:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/0*i6U7wfNPXtSxSoT9.png" /></figure><p>DFS use a <a href="https://hurna.io/academy/data_structures/stack.html">Stack (LIFO)</a></p><h3>Code</h3><pre>DFS(Maze maze, Node start, Node end)<br>{<br>  // Put the start node in the stack<br>  start.visite = true;<br>  Stack stack(start);</pre><pre>  // While there is node to be handled in the queue<br>  while (!stack.empty())<br>  {<br>    // Handle the node in the front of the line<br>    Node curNode = queue.pop();</pre><pre>    // Terminate if the goal is reached<br>    if (curNode == end)<br>      break;</pre><pre>    // Take unvisited neighbors in order <br>    // set its parent, mark as visited, and add to the queue<br>    auto neighbors = curNode.GetUnvisitedNeighbors();<br>    for (auto i = 0; i &lt; neighbors.size(); ++i)<br>    {<br>      neighbors[i].visite = true;<br>      neighbors[i].parent = curNode;<br>      stack.push(neighbors[i]);<br>    }<br>  }</pre><pre>  // Done ! At this point we just have to walk back from the end using the parent<br>  // If end does not have a parent, it means that it has not been found.<br>}</pre><h3>Recursive version</h3><p>The recursion of the DFS algorithm stems from the fact that we don’t actually finish checking a “parent” node until we reach a dead end, and inevitably pop off one of the “parent” node’s children from the top of the call stack. More than words, the code talks for itself ^^</p><pre>bool Recursive_DFS(Maze maze, Node start, Node end)<br>{<br>  // Terminate if the goal is reached<br>  if (start == end)<br>    return true;</pre><pre>  // Visite current node<br>  start.visite = true;</pre><pre>  // Take unvisited neighbors in order<br>  auto neighbors = start.GetUnvisitedNeighbors();<br>  for (auto i = 0; i &lt; neighbors.size(); ++i)<br>  {<br>    neighbors[i].parent = start;</pre><pre>    // Recurse and Terminate if the goal is reached<br>    if (Recursive_DFS(maze, neighbors[i], end)) return true;<br>  }</pre><pre>  return false;<br>}</pre><h3>Visualization</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FyXfwgmyNzGw%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DyXfwgmyNzGw&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FyXfwgmyNzGw%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/65de8aa1cd8939da753911f5e4e48081/href">https://medium.com/media/65de8aa1cd8939da753911f5e4e48081/href</a></iframe><h3>Dijkstra</h3><p>Pathfinding has gained prominence in the early 1950’s in the context of routing; that is, finding shortest directions between two or more nodes. In 1956, the Dutch software engineer Edsger Wybe Dijkstra created the best-known of these algorithms : <strong>Dijkstra</strong>.</p><blockquote>Dijkstra’s algorithm <strong>finds the shortest path from a root node to every other node</strong> (until the target is reached). <strong>Dijkstra is one of the most useful graph algorithms</strong>; furthermore, it can easily be modified to solve many different problems.</blockquote><p>Traversal algorithms such as <a href="https://hurna.io/academy/algorithms/maze_pathfinder/bfs.html">breadth-first-search</a> and <a href="https://hurna.io/academy/algorithms/maze_pathfinder/dfs.html">depth-first-search</a> explore all possibilities : they iterate over all possible paths until they reach the target. However, it may not be necessary to examine all possible paths; <strong>Dijkstra’s algorithm eliminates useless traversal using heuristics to find the optimal paths.</strong></p><h3>Some applications</h3><ul><li>Widely used in Network routing protocols.</li><li>In digital mapping services such as Google Maps.</li><li>In Biology by finding the network model in spreading of infectious diseases.</li><li>In finding the optimal agenda of flights.</li><li>In path planning for mobile robot transportation…</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*D_ipy21yCKZ_UYi4.png" /></figure><blockquote>Eg. used to compute a romantic riverside walk in Paris.</blockquote><h3>How To Build</h3><p>This algorithm begins with a root (or start) node and a queue of candidate nodes. At each step, we compute minimal distance between the root and each unvisited neighbors. Then, we add them to the queue; the one with the lowest distance is the next one that will be taken from the queue. This process repeats until a path to the destination has been found.</p><p>Since the lowest distance nodes are examined first, the first time the destination is found, the path to it will be the shortest path.</p><blockquote><strong>Minimizing the distance from the root node is our heuristic here.</strong></blockquote><p>Here is the distance map computed for a maze from the top left corner (root). You may notice that each connection between two adjacent nodes has a distance cost of 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/0*i_K7xNXDv5_ybCuR.png" /></figure><h3>Steps</h3><p>Let’s take a <strong>root node</strong> and note <strong>D the distance from a node to the root</strong>. Dijkstra’s algorithm will assign some initial distance values and improve them step by step.</p><ul><li>1. Set all node distance D to infinity except for the root (current) node which distance is 0.</li><li>2. Mark current node as visited and <strong>update D</strong> for all of its unvisited neighbors <strong>with the shortest distance</strong>.<br>Note: we can stop the algorithm here if we have reached the target node.</li><li>3. Add to the queue the unvisited neighbors and go back to step 2.</li></ul><blockquote><strong>Yes, one of the most useful and used algorithms is as simple as that !</strong></blockquote><p>As we have seen : by calculating and continually updating the shortest distance, the algorithm compiles the shortest path to the destination. A key part of this approach is maintaining an ordered line of nodes to visit next; to set up that part of the algorithm, we will use a <strong>priority queue</strong> (a regular queue with the ability to set priorities).</p><p>For Dijkstra’s algorithm, it is always recommended to use priority queue (or heap) as the required operations (extract minimum and decrease key) match with specialty this data structure. Here the priority is defined by D (the distance between a node and the root). <strong>Higher priorities are given for nodes with lower distance D.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/0*FzzV7i3w6X0KKjiH.png" /></figure><p>You may see it as a regular attraction queue with some people having access to shortcut heading to different checkpoints. A priority queue should have the following methods:</p><pre>// Add new element at the end of the queue<br>void enqueue(const T&amp; data, const int priority);</pre><pre>// Remove element from the beginning of the queue<br>void dequeue();</pre><pre>// Change the priority of the element in the queue.<br>void changePriority(const T&amp; item, const int priority);</pre><p>Now that we know all we need to know, here is the implementation (the visual explanation follows):</p><h3>Code</h3><pre>Dijkstra(Maze maze, Node start, Node end) {<br>    priority_queue queue();</pre><pre>    // Init all distances with infinity<br>    for (auto&amp;&amp; node : maze.nodes) node.distance = Infinity;</pre><pre>    // Distance to the root itself is zero<br>    start.distance = 0;</pre><pre>    // Init queue with the root node<br>    queue.add(start, 0);</pre><pre>    // Iterate over the priority queue until it is empty.<br>    while (!queue.isEmpty()) {<br>      curNode = queue.dequeue();  // Fetch next closest node<br>      curNode.discovered = true;  // Mark as discovered</pre><pre>      // Iterate over unvisited neighbors<br>      for (auto&amp;&amp; neighbor : curNode.GetUnvisitedNeighbors())<br>      {<br>        // Update minimal distance to neighbor<br>        // Note: distance between to adjacent node is constant<br>        const minDistance = <br>          Math.min(neighbor.distance, curNode.distance + 1);<br>        if (minDistance !== neighbor.distance) {<br>          neighbor.distance = minDistance;  <br>          neighbor.parent = curNode;        </pre><pre>          // Change queue priority of the neighbor <br>          if (queue.has(neighbor))<br>           queue.setPriority(neighbor, minDistance);<br>        }</pre><pre>        // Add neighbor to the queue for further visiting.<br>        if (!queue.has(neighbor)) <br>          queue.add(neighbor, neighbor.distance);<br>      }<br>    }</pre><pre>  // Done ! At this point we just have to walk back from the end using the parent<br>  // If end does not have a parent, it means that it has not been found.<br>}</pre><blockquote><strong>NOTE</strong><br>Dijkstra’s algorithm does not support negative distances. The algorithm assumes that adding a relationship to a path can never make a path shorter, an invariant that would be violated with negative distances.</blockquote><h3>Visualization</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FvkkFgqeEdXY%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DvkkFgqeEdXY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FvkkFgqeEdXY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e17461faf22fb3dd8756b355a1eada1/href">https://medium.com/media/4e17461faf22fb3dd8756b355a1eada1/href</a></iframe><h3><strong>A* (A-Star)</strong></h3><p>The <strong>A* (A-Star)</strong> algorithm improves on <a href="https://hurna.io/academy/algorithms/maze_pathfinder/dijkstra.html">Dijkstra’s</a> by finding the shortest path more quickly. It was invented by Peter Hart, Nils Nilsson, and Bertram Raphael (three American computer scientists) and described in their paper “A Formal Basis for the Heuristic Determination of Minimum Cost Paths” in 1968.</p><blockquote>A* pathfinding algorithm is arguably the best pathfinding algorithm when we have to find the shortest path between two nodes. <strong>A* is the golden ticket, or industry standard, that everyone uses.</strong></blockquote><p>Dijkstra’s Algorithm works well to find the shortest path, but it wastes time exploring in directions that aren’t promising. A* improves this by allowing the inclusion of extra information that the algorithm can use as part of the <strong>heuristic function</strong>:<br> — Dijkstra’s Algorithm use the distance from the root node.<br> — <strong>The A* algorithm uses both the actual distance from the root and the estimated distance to the goal.</strong></p><blockquote>That’s it !<br>In fact A* algorithm is just a variant of Dijkstra’s algorithm.</blockquote><h3>Applications</h3><p>As a variant of Dijkstra’s algorithm, A* is used everywhere : it is widely used in video games, in machine learning, navigation systems, autonomous vehicles, natural language processing (NLP) etc.</p><h3>How To Build</h3><p>A* selects the path that minimizes the following function : f(n)=g(n)+h(n), where:<br> — <strong>g(n)</strong> is the cost of the path from the starting point to node n (<a href="https://hurna.io/academy/algorithms/maze_pathfinder/dijkstra.html#build"><strong>Dijkstra distance</strong></a>).<br> — <strong>h(n)</strong> is the estimated cost of the path from node n to the destination node, as computed by the <strong>Manhattan distance</strong> in our case.</p><blockquote>Ok… but what’s the Manhattan distance ?</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*cjh3izgm5Ldt62_S.png" /></figure><p>The Manhattan distance (or Taxicab distance) origin is based on the well-known grid like street geography of the New York borough of Manhattan. It is <strong>the distance between two points in a grid based environment (with only horizontal and vertical moves)</strong>. The Manhattan distance is the simple sum of the horizontal and vertical moves, whereas the diagonal or “as the crow flies” distance might be computed by applying the Pythagorean theorem.</p><p>This distance is ideal for our mazes that allow 4-way movement (up, down, left, right).h(n)=|goal.x−root.x|+|goal.y−root.y|</p><p>Here are the distance maps computed (Manhattan, Dijkstra and A*) :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/0*PUBNu3Hc780AwdV4.png" /></figure><blockquote>Manhattan distance map (from right bottom destination) : h(n)<br>We may reinforce the Manhattan heuristic by using a factor. For instance : h(n)</blockquote><h3>Steps</h3><blockquote><strong>As simple as </strong><a href="https://hurna.io/academy/algorithms/maze_pathfinder/dijkstra.html#build"><strong>Dijkstra</strong></a><strong>, the only change is the cost function (we add the Manhattan distance) !</strong></blockquote><h3>Code</h3><pre>AStar(Maze maze, Node start, Node end) {<br>    priority_queue queue();</pre><pre>    // Init all distances with infinity<br>    for (auto&amp;&amp; node : maze.nodes) {<br>      node.distance = Infinity;<br>      node.rootDistance = Infinity;</pre><pre>      // Note: we may reinforce the manhattan heuristic<br>      node.manhattanD = 2 * <br>        (Math.abs(end.x - node.x) + Math.abs(end.y - node.y));<br>    }</pre><pre>    // Distance to the root itself is zero<br>    start.rootDistance = 0;</pre><pre>    // Init queue with the root node<br>    queue.add(start, 0);</pre><pre>    // Iterate over the priority queue until it is empty.<br>    while (!queue.isEmpty()) {<br>      curNode = queue.dequeue();  // Fetch next closest node<br>      curNode.discovered = true;  // Mark as discovered</pre><pre>      // Iterate over unvisited neighbors<br>      for (auto&amp;&amp; neighbor : curNode.GetUnvisitedNeighbors())<br>      {<br>        // Update root minimal distance <br>        neighbor.rDistance =<br>          Math.min(neighbor.rootDistance, curNode.rootDistance + 1);<br>        const minDistance =<br>          Math.min(neighbor.distance, <br>            neighbor.rootDistance + neighbor.manhattanD);<br>        <br>        if (minDistance !== neighbor.distance) {<br>          neighbor.distance = minDistance;  <br>          neighbor.parent = curNode;        </pre><pre>          // Change queue priority of the neighbor <br>          if (queue.has(neighbor)) <br>            queue.setPriority(neighbor, minDistance);<br>        }</pre><pre>        // Add neighbor to the queue for further visiting.<br>        if (!queue.has(neighbor)) <br>          queue.add(neighbor, neighbor.distance);<br>      }<br>    }</pre><pre>  // Done ! At this point we just have to walk back from the end using the parent<br>  // If end does not have a parent, it means that it has not been found.<br>}</pre><h3>Visualization</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FwnNQ_1RxWJA%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DwnNQ_1RxWJA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FwnNQ_1RxWJA%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/4536bc782f364bed63446dd76fbaef99/href">https://medium.com/media/4536bc782f364bed63446dd76fbaef99/href</a></iframe><p><em>To better understand the differences between these algorithms and their operations, you may use </em><a href="https://demo.hurna.io/#path=pathfinding/dfs"><strong><em>H.urna Explorer </em></strong></a><em>: our interactive platform, which will allow you to manipulate and compare them.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ebad85d4c6b" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/pathfinding-algorithms-the-four-pillars-1ebad85d4c6b">Pathfinding algorithms : the four Pillars.</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>