<?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 Tanishq Vyas on Medium]]></title>
        <description><![CDATA[Stories by Tanishq Vyas on Medium]]></description>
        <link>https://medium.com/@tanishqvyas069?source=rss-7132cd1d5ed0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*3PWlHPI64uRm07uoVSwmww.jpeg</url>
            <title>Stories by Tanishq Vyas on Medium</title>
            <link>https://medium.com/@tanishqvyas069?source=rss-7132cd1d5ed0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 22:57:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tanishqvyas069/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[All about git stash]]></title>
            <link>https://levelup.gitconnected.com/all-about-git-stash-8a9460fdc01e?source=rss-7132cd1d5ed0------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a9460fdc01e</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[git-stash]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[gitlab]]></category>
            <category><![CDATA[gi̇t]]></category>
            <dc:creator><![CDATA[Tanishq Vyas]]></dc:creator>
            <pubDate>Mon, 21 Nov 2022 17:51:26 GMT</pubDate>
            <atom:updated>2022-11-22T02:00:12.869Z</atom:updated>
            <content:encoded><![CDATA[<p>A simple to understand step by step guide to understanding git stash</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LOzYDcYiqSI4zG13" /><figcaption>Photo by <a href="https://unsplash.com/ja/@yancymin?utm_source=medium&amp;utm_medium=referral">Yancy Min</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><a href="https://git-scm.com/">Git</a> is one of the must-have skills under one’s belt. Having a good grasp of the concepts of Git not only helps you effectively manage your changes but also improves the overall productivity and workflow. This article would aim to cover one of the many useful git commands, namely, <a href="https://git-scm.com/docs/git-stash">git stash</a>.</p><p>I personally have found it very useful while working on various projects.</p><p>With that being said, let’s git cracking!</p><h3>Scenario</h3><p>Have you ever found yourself in a position where you</p><ul><li>Made changes in the wrong branch but haven’t commited them yet? And now you wish to somehow shift these changes to the branch of your choice?</li><li>Are in the middle of implementing a new change which is not yet complete but you have to urgently take up a new task because of its high priority?</li><li>Want a clean working tree because of one or the other reason but do not wish to throw away your changes?</li><li>Simply wish to save your uncommited changes to be able to view in future?</li></ul><p>Then do not worry because <a href="https://git-scm.com/docs/git-stash">git stash</a> is all you need!</p><h3>What is git stash?</h3><p>It is a command that allows you to save your uncommited changes in a stack like data structure. You could then apply those changes back to your working tree as and when needed.</p><p>This allows for a flexible workflow while working on several tasks at once.</p><h3>Commands to remember</h3><p>The following section contains the various commands associated to stashing and the nitty gritty details associated with them</p><h4>1. List all the stashes</h4><pre>git stash list</pre><p>Depending on whether you have something in the stash, it will give one of the following two outputs</p><ul><li>Empty line: No stashes</li><li>List of Stashes with the index: One or more stashes</li></ul><p>More on how to read this list in the upcoming section.</p><h4>2. Save changes to stash</h4><p>Consider the following scenario where you may have two kind of changes, namely</p><ul><li>Changes in tracked files</li><li>Changes in untracked files</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h75O89cQe7VvKvxzVISwvQ.png" /></figure><p>To save the changes to stash one must simply type</p><pre>git stash</pre><p>This creates the following stash and rolls back the working tree to HEAD.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*plhivrUx08OT_4vPSO1W6Q.png" /></figure><p>Here the number present within the curly braces indicates the index of that particular stash. In this case since the stash stack was empty, it is present at the <strong>top of the stack i.e. index 0</strong>. As and when new changes are saved in the stash, the index of the previous changes keeps incrementing. Just like a stack (FIFO) where the top of the stack is at index 0.</p><p>“<strong>WIP on main</strong>” means work in progress on branch main</p><p>And the <strong>eeefba5 </strong>and<strong> commit 2,</strong> are the ID and message of the previous commit, respectively.</p><p>Hence, to sum up, the generic format would be something like</p><pre>stash@{&lt;index of stash&gt;}: WIP on &lt;branch name&gt;: &lt;SHA-1 hash of the commit&gt; &lt;commit message of the last commit&gt;</pre><p><strong>Problem 1</strong></p><p>By default the changes introduced in untracked files are not stashed. Hence, to include those in the stash, one must instead use the --include-untracked flag. This would then save the untracked changes along with the tracked changes within the stash.</p><pre>git stash --include-untracked</pre><p><strong>Problem 2</strong></p><p>Consider we make another change in the working tree and stash the same. That would cause the stash to look like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DtFGjDYgrWBD1xEHIA2Xdw.png" /></figure><p>As we can see, both of them look identical on the surface level. This makes it harder for someone to identify what changes are associated to which stashed item. One must look into the actual changes to determine which stash to apply.</p><p>Hence, adding meaningful message to a stashed item, rather than keeping the default message, proves helpful. To provide a custom message use the following command</p><pre>git stash push -m &quot;test message&quot; --include-untracked</pre><p>This would result in our stash looking like this instead of what we had earlier without any custom message</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FUcHLUQILT0VI2jctsCYwA.png" /></figure><p><strong>Important things to note</strong></p><ul><li>The command git stash save was officially deprecated in the <a href="https://github.com/git/git/blob/master/Documentation/RelNotes/2.16.0.txt#L34">2.16.0 release</a> of Git. Hence, I will not be covering that in this article. A good reference would be <a href="https://stackoverflow.com/a/71040797/11597114">this</a> and <a href="https://stackoverflow.com/a/44681952/11597114">this</a> answer on stackoverflow.</li></ul><p>The commands git stash create and git stash store have been</p><h4>3. Applying changes to working tree</h4><p>Now that we have changes saved in our stash, we might want to apply them back at the correct place. To do that simply type</p><pre>git stash pop</pre><p>A few things to note about the behaviour of this command</p><ul><li>This applies the saved changes present on the top of the stack i.e. index 0 of the stash</li><li>This deletes those changes from the stash. Hence decrementing the index of all other saved changes by 1 respectively.</li></ul><p>If you wish to apply a change which is present a n-th index then use the following command</p><pre>git stash apply stash@{N}</pre><p>Where <strong>N</strong> is the index of the saved change you wish to apply. One thing to note about this command is that this does not delete the saved stash.</p><p>An additional note</p><pre>git stash branch &lt;branchname&gt; stash@{N}</pre><p>Creates and checks out a new branch named &lt;branchname&gt; starting from the commit at which the &lt;stash&gt; was originally created, applies the changes recorded in &lt;stash&gt; to the new working tree and index. If that succeeds, and &lt;stash&gt; is a reference of the form stash@{&lt;revision&gt;}, it then drops the &lt;stash&gt;. More on this can be found <a href="https://git-scm.com/docs/git-stash#Documentation/git-stash.txt-branchltbranchnamegtltstashgt">here</a>.</p><h4>4. Deleting a saved change from the stash</h4><p>In case you feel that a certain saved change in the stash is of no use and you wishto delete it, you may use the following command</p><pre>git stash drop stash@{N}</pre><p>Where <strong>N</strong> is the index of the saved change you wish to delete form the stash.</p><p>In case, you wish to delete all the saved changes and empy the stash then use the following command</p><pre>git stash clear</pre><h3>Additional references and reads</h3><ol><li><a href="https://stackoverflow.com/a/57008221/11597114">Difference between <em>git stash save</em> and <em>git stash store</em></a></li><li><a href="https://stackoverflow.com/questions/28635989/what-is-the-purpose-of-git-stash-create-and-git-stash-store">Purpose of <em>git stash create</em> and <em>git stash store</em></a></li><li><a href="https://stackoverflow.com/questions/44680028/whats-the-difference-between-git-stash-save-and-git-stash-push">Difference between <em>git stash save</em> and <em>git stash push</em></a></li></ol><p>I hope I was able to provide atleast one piece of useful information throught this article. If you want me to cover any other useful <a href="https://git-scm.com/">Git</a> command which is beyond the basics, please feel free to drop names in the comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a9460fdc01e" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/all-about-git-stash-8a9460fdc01e">All about git stash</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[Making the perfect commit]]></title>
            <link>https://levelup.gitconnected.com/making-the-perfect-commit-b2d98e82bf48?source=rss-7132cd1d5ed0------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2d98e82bf48</guid>
            <category><![CDATA[commit]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[gitlab]]></category>
            <category><![CDATA[project-management]]></category>
            <dc:creator><![CDATA[Tanishq Vyas]]></dc:creator>
            <pubDate>Sun, 20 Nov 2022 09:45:55 GMT</pubDate>
            <atom:updated>2022-11-20T20:16:16.182Z</atom:updated>
            <content:encoded><![CDATA[<p>Points to keep in mind to make the perfect commit</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*u5PsBf9xxGmopIAY" /><figcaption>Photo by <a href="https://unsplash.com/ja/@yancymin?utm_source=medium&amp;utm_medium=referral">Yancy Min</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As a developer, you might have sat someday pondering “What does a perfect commit look like?”</p><p>If yes, then this article is for you!</p><p>Please bear in mind that these are solely my views. These may differ from developer to developer. The ultimate goal here is to be able to improve the productivity and make the change management much more effective and easier.</p><p>With that being said let’s git started!</p><h3>Features of a Perfect Commit</h3><p>According to me the following would characterize a perfect commit:</p><ol><li>A single focused change.</li><li>Added/updated comments that elaborates the implementation wherever necessary.</li><li>Added/updated documentation that explains the change.</li><li>Relevant tests that assures the proper functioning of the change introduced.</li><li>A small yet apt commit message. The commit message must be linked to the issue/ticket.</li><li>It must be a unit that is stable and could be deployed.</li></ol><p>In the upcoming sections of this article I will be illustrating how one could ensure that all the steps are followed as much as possible.</p><h3>1. Single focused change</h3><p>The “change” here in question can be anything from a bug fix, to a feature implementation or a typo correction. Whatever it may be, one must ensure that things that have been changed/newly added/deleted are all in direct accordance with that change.</p><p>No extra changes which are not relevant to the current change must be added in the commit.</p><p>The goal here is to be able to achieve something that can be</p><ol><li>Easily &amp; atomically reviewed in PRs, via <a href="https://git-scm.com/docs/git-blame"><em>git blame</em></a> or <a href="https://git-scm.com/docs/git-blame"><em>git bisect</em></a></li><li>Easily reverted, should the situation call for it, using <a href="https://git-scm.com/docs/git-revert"><em>git revert</em></a></li><li>Easily <a href="https://git-scm.com/docs/git-cherry-pick"><em>cherry picked</em></a> into other branches</li></ol><p>One could achieve this by knowing</p><ol><li>What not to commit. The project must have a <a href="https://www.atlassian.com/git/tutorials/saving-changes/gitignore">.gitignore</a> file.</li><li>How to stage a specific file for the commit</li><li>How to stage specific lines of a file for the commit instead of the entire file (Yes, this is possible! With the help of <a href="https://git-scm.com/docs/git-add#Documentation/git-add.txt--p"><em>git add -p</em></a>)</li></ol><p>One must avoid falling for the trap of using</p><pre>git add .</pre><h3>2. Relevant comments</h3><p>The best piece of code is the one which requires no additional comments. However, as the complexity and scale of the application grows and One must avoid falling for the trap of usingwe are not the only individual working on the codebase, it is a necessity to add comments.</p><p>A few points must be kept in mind while writing appropriate comments in your code must</p><ol><li>Not duplicate the code. Such comments are rendered useless because of their redundancy.</li><li>Not be vague. They must have only one interpretation and should leave no scope of doubt.</li><li>Dispel confusion not cause it.</li><li>Must provide links to the references/original source code used while writing the piece of code.</li><li>Must be used to mark incomplete implementations.</li></ol><pre>// TODO : Add fallback values for unavailable keys</pre><p>6. Provide documentation comments, function comments and logic comments wherever necessary.</p><p>7. Use appropriate code annotations or tags while writing comments. for example Javascript uses <a href="https://jsdoc.app/about-getting-started.html"><em>JSDoc</em></a><em> </em>whereas JAVA uses<em> </em><a href="https://www.oracle.com/be/technical-resources/articles/java/javadoc-tool.html"><em>JavaDoc</em></a><em>.</em></p><p>8. Improve productivity with the use of appropriate extensions such as <a href="https://marketplace.visualstudio.com/items?itemName=Stepsize.stepsize">StepSize</a> or <a href="https://marketplace.visualstudio.com/items?itemName=aaron-bond.better-comments">Better Comments</a> for improved issues and comments management.</p><p>For further read on good commenting practices please refer <a href="https://stackoverflow.blog/2021/12/23/best-practices-for-writing-code-comments/"><em>this</em></a><em>.</em></p><h3>3. Relevant documentation</h3><p>A complete, unambiguous and precise documentation is a developer’s friend. One must ensure that not just the code that is being written but also the associated documentation is simultaneously updated and versioned.</p><p>This also includes updating the postman collections, SLA agreements, etc being used by the teams.</p><h3>4. Simultaneous testing</h3><p>Test Driven Development or TDD for short is quite well known development practice. However, you must not stick to the notion that this is the only way of doing things.</p><p>The ultimate goal of tests is to ensure that nothing new that was added broke something that already worked. When it comes to testing an enterprise level application, one may find it quite the herculean task to test all possible workflows manually.</p><p>It is thus advised to ensure proper testing framework(s) are in place and tests are continuously added/updated as and when changes are made to the codebase.</p><h3>5. Appropriate commit message</h3><p>The one thing which we developers might find ourselves struggling with is coming up with a nice yet short commit message. Some of us even try to explain the entire implementation of the change within the commit message. However, I would advise the following</p><ol><li>Always include the issue/ticket number in your commit message. This helps one associate the change to the respective task. This issue/ticket would then contain</li></ol><ul><li>Further description of the change.</li><li>Steps to validate and/or reproduce the issue.</li><li>A chain of conversation explaining what necessitates this change and what all findings have been made while implementing the change.</li><li>The conclusion and why this approach was decided.</li><li>Finally, the proof that the implemented change works.</li></ul><p>Keeping this discussion away from the commit message gives us the liberty to be as descriptive as possible. Instead of writing a lenghty commit message. Always aim for one that just acts as a title.</p><p>2. Follow a standard of writing commit messages. For example I prefer having my commit messages in the format</p><pre>git commit -m &quot;&lt;Issue-number&gt;; &lt;Message&gt;&quot;</pre><p>The message usually includes an action verb such as fixed, implemented, resolved, etc that indicates what is the primary thing that was done followed by what was done.</p><p>Examples</p><ul><li>“#53; Bumped up node version from 13.14.0 to 16.16.0”</li><li>“#47, #69; Fixed conflicting peer dependencies for react@18”</li><li>“#12; Implemented RBAC”</li><li>“#13; Reverted #12 RBAC implementation”</li></ul><p>This is the one which I follow. Your team may come up with their own standard of writing messages. The concept of <a href="https://www.conventionalcommits.org/en/v1.0.0/#summary">conventional commits</a> or something similar and standardized must be used. Additional read for this point could be <a href="https://dev.to/visuellverstehen/new-git-guidelines-we-have-switched-to-conventional-commits-1p0c"><em>this</em></a><em>.</em></p><h3>6. Deployable unit of code</h3><p>This is one of the most crucial things to keep in mind. Every commit that you make must be deployment worthy. Never commit the code that breaks.</p><p>The commit must pass have a passing build, static code analysis passing, vulnerability assessment passing, uniform formatting based on the team’s formatitng style guide and any other relevant checks must be passed which are put in place by the team. One could setup pre-commit hooks using <a href="https://typicode.github.io/husky/#/">husky</a> to ensure that the checks are run before the commit is made to avoid any improper commits.</p><p>These checks could also be enforced on the pull requests where the changes are not allowed to be merged unless all checks have passed.</p><p>This is one of the most common mistake that I have seen new developers make. Where they commit an incomplete change because of one or the other reason.</p><p>In case you find yourself in a position where you are in the middle of making your changes but must urgently shift to another task then kindly <a href="https://git-scm.com/docs/git-stash"><em>stash</em></a> your changes instead of commiting incomplete changes. One can always come back to the stashed changes and continue working on them.</p><p>I hope I was able to provide you with atleast one piece of useful information which you did not know before. If you have any good suggestions to add onto this, please leave a comment explaining the same. I would be happy to include them in the article above.</p><p><em>That’s All Folks! Until next time</em>👋</p><h3>Level Up Coding</h3><p>Thanks for being a part of our community! Before you go:</p><ul><li>👏 Clap for the story and follow the author 👉</li><li>📰 View more content in the <a href="https://levelup.gitconnected.com/?utm_source=pub&amp;utm_medium=post">Level Up Coding publication</a></li><li>🔔 Follow us: <a href="https://twitter.com/gitconnected">Twitter</a> | <a href="https://www.linkedin.com/company/gitconnected">LinkedIn</a> | <a href="https://newsletter.levelup.dev/">Newsletter</a></li></ul><p>🚀👉 <a href="https://jobs.levelup.dev/talent/welcome?referral=true"><strong>Join the Level Up talent collective and find an amazing job</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2d98e82bf48" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/making-the-perfect-commit-b2d98e82bf48">Making the perfect commit</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[A glimpse of the Sound]]></title>
            <link>https://tanishqvyas069.medium.com/a-glimpse-of-the-sound-7c3ff5b16bf?source=rss-7132cd1d5ed0------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c3ff5b16bf</guid>
            <category><![CDATA[spectrogram]]></category>
            <category><![CDATA[mel-spectrogram]]></category>
            <category><![CDATA[sound]]></category>
            <dc:creator><![CDATA[Tanishq Vyas]]></dc:creator>
            <pubDate>Thu, 28 Jul 2022 14:34:16 GMT</pubDate>
            <atom:updated>2022-07-28T14:34:16.832Z</atom:updated>
            <content:encoded><![CDATA[<p>An introduction to Spectrograms and Mel-spectrograms</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*f4keV_ewlrSlj3Xo" /><figcaption>Photo by <a href="https://unsplash.com/@pawel_czerwinski?utm_source=medium&amp;utm_medium=referral">Pawel Czerwinski</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What is Sound?</h3><p>In essence, the sound is a signal. A signal is nothing more than the variation of a certain quantity over time. In the case of sound, the quantity is <strong>air pressure</strong>.</p><p>Sound is essentially a vibration that propagates through a medium thus causing a disruption in the medium itself. It is essentially a mechanical wave that carries energy from one point in space to another formed due to a vibrating source that in turn produces vibration of the particles of the medium.</p><figure><img alt="Compression and Rarefaction" src="https://cdn-images-1.medium.com/max/910/1*iDpYmElDyIndEcyvn5wO-A.png" /></figure><p>It propagates as a series of alternate compressions and rarefactions. <strong>Compression </strong>is the region where particles of the medium are close together and <strong>Rarefaction</strong> is a region where these particles far apart. When a human ear receives these vibrations, we are able to perceive sound.</p><h3>How do we visualize sound?</h3><p>One of the most commonly known methods to visualize a sound wave is by plotting a <strong>Waveform</strong>. This is essentially a plot that depicts pressure variations or amplitude variations of a sound wave with time. An example can be seen below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*VrOdusKi1AQzWC-TKjqxog.png" /></figure><p>However intriguing, this kind of plot does not give us a whole lot of information about the sound itself. Thus a better approach to look at the same was developed, namely <strong>Spectrogram</strong>.</p><h4>What is a Spectrogram?</h4><p>A Spectrogram is a plot that shows the signal strength (or loudness) over time for various frequencies present in the sound wave.</p><figure><img alt="Spectrogram" src="https://cdn-images-1.medium.com/max/999/1*I07h6SzNZYeee4Q54Fxhpg.png" /></figure><p><strong>Time</strong>, being the independent variable, is plotted on the X-axis. Different <strong>frequencies</strong> present in the audio waveform are plotted on the Y-axis. A third dimension, represented using colors, is used to depict the <strong>signal strength</strong> (or loudness) for a given frequency at a given point in time. The color scheme may vary from spectrogram to spectrogram but the essential idea behind each remains constant.</p><p>The frequency representation in a spectrogram is linear in scale. However, humans perceive pitch (frequencies) logarithmically. Thus, we require a time-frequency representation that is perceptually relevant in terms of signal strength as well as frequency (amplitude or loudness) representation.</p><p>The vanilla spectrograms only satisfy the former of the two requirements. This is why we came up with a slightly different variation of the vanilla spectrogram, namely the Mel-spectrogram.</p><h4>What is Mel-spectrogram?</h4><p>The term Mel-spectrogram is formed by the conjugation of two terms, <strong>Mel </strong>&amp; <strong>Spectrogram</strong>. We all know what a spectrogram is, so, let’s talk about what exactly <strong>mel</strong> stands for.</p><figure><img alt="Mel Scale" src="https://cdn-images-1.medium.com/max/910/1*cCDTUg8eN1zuLvDp3mpywA.png" /></figure><p>The term <strong>Mel</strong> (taken after the word melody) is a perceptually linear scale of frequencies where the <strong>equal distance on the mel scale corresponds to equal perceptual distance. </strong>It is a mapping from the usual Hertz scale in a way that aligns with the way humans perceive sound. The experts standardized it such that <strong>1000Hz = 1000 Mel</strong>.</p><p>In order to convert the Hertz scale to the Mel scale, we can use the following relation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*EW3tjLiG0aE1bJEfrJWOTg.png" /></figure><p>However fascinating, the question,</p><p><strong><em>How did we arrive at this particular mapping?</em></strong></p><p>may sound, but this topic is beyond the scope of our current discussion.</p><p>Thus, a <strong>Mel-spectrogram</strong> is a spectrogram where the frequencies are converted to the mel scale.</p><h4>References</h4><ol><li><a href="https://en.wikipedia.org/wiki/Mel_scale">Mel-Scale Wikipedia</a></li><li><a href="https://www.youtube.com/watch?v=9GHCiiDLHQ4&amp;t">Mel-spectrogram explained</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c3ff5b16bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Segment Tree]]></title>
            <link>https://levelup.gitconnected.com/segment-tree-640d1e0fee6f?source=rss-7132cd1d5ed0------2</link>
            <guid isPermaLink="false">https://medium.com/p/640d1e0fee6f</guid>
            <category><![CDATA[segment-tree]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[generic-programming]]></category>
            <category><![CDATA[range-query]]></category>
            <category><![CDATA[range-sum-query]]></category>
            <dc:creator><![CDATA[Tanishq Vyas]]></dc:creator>
            <pubDate>Tue, 04 May 2021 05:10:59 GMT</pubDate>
            <atom:updated>2021-05-04T11:46:29.509Z</atom:updated>
            <content:encoded><![CDATA[<p>A comprehensive introduction to Segment Tree</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GU2swq5JtrD1Jcxe" /><figcaption>Photo by <a href="https://unsplash.com/@ffstop?utm_source=medium&amp;utm_medium=referral">Fotis Fotopoulos</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>1. What is a Segment Tree?</h3><p>Let’s say we have an array<strong> A</strong> of size <strong>N</strong>. A <strong>segment</strong> of the array is a contiguous part of an array in form <strong>A[i : j]</strong> such that <strong>0 ≤ i ≤ j ≤ N-1</strong>.</p><p>A <strong>segment tree</strong> is essentially a binary tree in whose nodes we store the information about the segments of a linear data structure such as an array. Do not worry about what kind of information as of now. We shall take a look at that in the later sections of this article.</p><ul><li>The root node of the segment tree would contain the information about segment <strong>A[0 : N-1]</strong></li><li>The left child of the root node would contain the information about segment <strong>A[0 : (N-1)/2] </strong>and similarly,</li><li>The right child of the root node would contain the information about segment <strong>A[ 1+((N-1)/2) : (N-1) ] </strong>and so on.</li></ul><p>In simpler terms the root node contains information about the whole array, its left child contains a similar kind of information about the left half of the array, and the right child of the root node will contain the information about the right half of the array and so on. Thus at each step (level of the tree), we divide the segment into two halves and the further children nodes contain the information about these two halves.</p><p>This continues till we reach the leaf nodes which contain the element of the array <strong>A</strong> itself. The <strong>i-th</strong> leaf node contains <strong>A[i]</strong>. Thus we can say that there will be <strong>N </strong>leaf<strong> </strong>nodes and the height of the tree will be log <strong>N </strong>to the base 2.</p><p><strong>Note: </strong>Once a segment tree is built for an array, its structure cannot be changed. We are allowed to update the values of the nodes but we cannot change the structure of the Segment Tree. That is to say, we cannot add more elements to the array and expect the segment tree to update. In that case, we will have to create a new segment tree altogether. However, we are allowed to update the values of the array and the segment tree shall be updated accordingly.</p><p>Segment Trees allow for the following two operations:</p><ul><li><strong>Update : </strong>This operation allows us to update the values of array <strong>A</strong> and reflect the corresponding changes in the segment tree.</li><li><strong>Query : </strong>This operation allows us to perform a range query on the array. For example, let&#39;s say we have an array of size 15 and we wish to find the maximum element in the segment of an array with start index as <strong>3</strong> and end index <strong>9</strong>. This is an example of a range query.</li></ul><p>Thus we can say that a segment tree comes in handy when we have a lot of range-based queries to be performed on an array along with value updates on the same array. The process of creation of a segment tree takes some time but once it&#39;s done, the operation of range queries becomes very fast.</p><h3>2. What kind of information does a segment tree hold?</h3><p>Now that we have a basic understanding of the structure of the segment tree let us have a look at what kind of information does a segment tree hold.</p><p>Consider an array <strong>A = [1, 4, 5, 8, 0, 13]</strong></p><p>Now a segment tree is always associated with a piece of certain information that is directly linked with the kind of range queries we wish to perform. A couple of them are as follows:</p><ul><li>Find the sum/product of elements of an array in the range A[i : j]</li><li>Find the maximum/minimum element in the range A[i : j]</li><li>Find the count of even/odd/prime etc, numbers in the range A[i : j]</li></ul><p>there can be many others depending upon the usage. Let us have a look at how we can make use of a segment tree to find the <strong>sum of elements in a given range</strong>.</p><h3>3. Creation of Segment Tree</h3><p>Let’s say we have an array <strong>A = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] </strong>and we wish to find the sum of elements in a given range. Then each node would store the sum of its children nodes, except the leaf nodes which store the array elements.</p><p>Then the segment tree for the same would look something like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pG4eayBxBQCjAd43NROV4Q.png" /></figure><p>The red node being the root node, the blue nodes being the internal nodes and the green nodes being the leaf nodes. Each node contains information about a particular segment of the array. In this example,</p><ul><li>Root node contains the sum of all the elements of the array</li><li>The left child of the root node contains the information about the sum of the left half of the array i.e. <strong>[1, 2, 3, 4, 5]</strong>. Its left child in turn contains the sum of the segment <strong>[1, 2, 3] </strong>and the right child contains the sum of the segment <strong>[4, 5]</strong> and so on.</li><li>The right child of the root node contains the information about the sum of the left half of the array i.e. <strong>[6, 7, 8, 9, 10]</strong>. Its left child in turn contains the sum of the segment <strong>[6, 7, 8] </strong>and the right child contains the sum of the segment <strong>[9, 10]</strong> and so on.</li></ul><p>If we wanted to compute, let&#39;s say, the maximum element then we would be storing the maximum element in each segment in the corresponding nodes. Thus before building the Segment Tree one must figure out the intent behind building the tree and the type of values to be stored in the tree’s nodes.</p><p>Thus we can also notice that a segment tree is always going to be a full binary tree i.e. each node either has 2 or 0 children.</p><h3>References</h3><ul><li><a href="https://www.hackerearth.com/practice/data-structures/advanced-data-structures/segment-trees/tutorial/">Segment Trees</a></li><li><a href="https://www.geeksforgeeks.org/segment-tree-set-1-sum-of-given-range/">Segment Trees (recursive implementation)</a></li><li><a href="https://www.geeksforgeeks.org/iterative-segment-tree-range-minimum-query/">Segment Trees (iterative implementation)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=640d1e0fee6f" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/segment-tree-640d1e0fee6f">Segment Tree</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[Dynamic Programming: Equal Sum Partition Problem]]></title>
            <link>https://levelup.gitconnected.com/dynamic-programming-equal-sum-partition-problem-b5059caf46bb?source=rss-7132cd1d5ed0------2</link>
            <guid isPermaLink="false">https://medium.com/p/b5059caf46bb</guid>
            <category><![CDATA[subset-sum-problem]]></category>
            <category><![CDATA[tabulation]]></category>
            <category><![CDATA[dynamic-programming]]></category>
            <category><![CDATA[equal-sum-partition]]></category>
            <dc:creator><![CDATA[Tanishq Vyas]]></dc:creator>
            <pubDate>Thu, 19 Nov 2020 14:24:21 GMT</pubDate>
            <atom:updated>2020-11-20T16:14:38.933Z</atom:updated>
            <content:encoded><![CDATA[<h4>Dynamic Programming Problem #3 : Equal Sum Partition</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wefH7vhZCrp2CO-o" /><figcaption>Photo by <a href="https://unsplash.com/@emilep?utm_source=medium&amp;utm_medium=referral">Emile Perron</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Before starting up with the Equal Sum Partition Problem, I would highly recommend you to read this introduction to <a href="https://medium.com/swlh/dynamic-programming-9a5e60fb7245"><strong>Dynamic Programming</strong></a>. Here I have covered the basic method on how to approach a DP based problem. We will be using the same concepts to solve the <strong>Equal Sum Partition Problem</strong>. I’d also highly recommend you to go through the <a href="https://tanishqvyas069.medium.com/dynamic-programming-subset-sum-c386126621cd"><strong>Subset Sum Problem</strong></a><strong> </strong>since it’s the parent problem for <strong>Equal Sum Partition Problem</strong>.</p><p>With that being said, let’s get started.</p><h3>1. What is Equal Partition Sum Problem ?</h3><p>Given a set of <strong>N </strong>non-negative integers, determine if the set can be partitioned into two subsets such that the sum of the elements in each of the two subsets is equal. Return 1 if there exists such partition, otherwise return 0.</p><pre>Let&#39;s say we have</pre><pre>nums = [2, 8, 9, 3]</pre><pre>Thus here subsets {2, 9} and {8, 3} form such partitions where the sum of elements in the both the sets is equal. Which in this case is </pre><pre>2 + 9 = 11<br>8 + 3 = 11</pre><pre>Thus we return True</pre><h3>2. How should we approach ?</h3><p>If you would have read this article on <a href="https://tanishqvyas069.medium.com/dynamic-programming-subset-sum-c386126621cd"><strong>Subset Sum Problem</strong></a><strong>, </strong>then you would be easily able to tell the reason why that problem is it’s parent. The current problem is a slight variation of the above stated parent problem.</p><p>Now, let’s assume that the sum of the elements in the given set is <strong>S</strong>.</p><p>Thus if there is a possibility of a partition which results in equal sum subsets then they must follow the following relation</p><p><strong>S = s1 + s2</strong></p><p>where <strong>s1</strong> and <strong>s2</strong> are the sum of elements of <strong>subset 1</strong> and <strong>subset 2</strong> respectively. Also <strong>s1 is equal to s2</strong>.</p><p><strong>S = 2*s1</strong></p><p>or</p><p><strong>S = 2*s2</strong></p><p>Thus we can easily say that if the sum <strong>S</strong> of the set is an even number, then there exists a possibility that a partition matching the above stated conditions can be made. Otherwise for a case where <strong>S</strong> is odd, no such partitions can be made.</p><p>Thus the whole problem reduces to finding <a href="https://tanishqvyas069.medium.com/dynamic-programming-subset-sum-c386126621cd"><strong>Subset Sum Problem</strong></a><strong> </strong>for the given set with the target sum = <strong>S/2</strong>.</p><p>So here’s how the solution for the same would look like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l6_CGzn4m7OOEKEvcIMshw.png" /></figure><p>I would highly recommend you to go through the <a href="https://tanishqvyas069.medium.com/dynamic-programming-subset-sum-c386126621cd"><strong>Subset Sum Problem</strong></a><strong> </strong>(this will be suffice)<strong> </strong>in order to fully understand how to write the above given solution. With this we have come to an end of <strong>Equal Sum Partition Problem</strong>. You can practice coding it yourselves <a href="https://leetcode.com/problems/partition-equal-subset-sum/">here</a>.</p><p>Thank You</p><h4>Other Articles</h4><ol><li><a href="https://medium.com/swlh/dynamic-programming-9a5e60fb7245">Getting Started with Dynamic Programming</a></li><li><a href="https://medium.com/@tanishqvyas069/dynamic-programming-0-1-knapsack-5af91763b6d5">0–1 Knapsack Problem | Dynamic Programming</a></li><li><a href="https://tanishqvyas069.medium.com/dynamic-programming-subset-sum-c386126621cd">Subset Sum Problem | Dynamic Programming</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5059caf46bb" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/dynamic-programming-equal-sum-partition-problem-b5059caf46bb">Dynamic Programming: Equal Sum Partition Problem</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[Dynamic Programming: Subset Sum]]></title>
            <link>https://levelup.gitconnected.com/dynamic-programming-subset-sum-c386126621cd?source=rss-7132cd1d5ed0------2</link>
            <guid isPermaLink="false">https://medium.com/p/c386126621cd</guid>
            <category><![CDATA[subset-sum-problem]]></category>
            <category><![CDATA[dynamic-programming]]></category>
            <category><![CDATA[tabulation]]></category>
            <category><![CDATA[memoization]]></category>
            <category><![CDATA[recursion]]></category>
            <dc:creator><![CDATA[Tanishq Vyas]]></dc:creator>
            <pubDate>Wed, 18 Nov 2020 18:56:38 GMT</pubDate>
            <atom:updated>2021-11-01T23:59:49.875Z</atom:updated>
            <content:encoded><![CDATA[<h3>Dynamic Programming: Subset Sum Problem</h3><h4>Dynamic Programming Problem #2 : Subset Sum</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*45xYjQ6j3i-qitLh" /><figcaption>Photo by <a href="https://unsplash.com/@codestorm?utm_source=medium&amp;utm_medium=referral">Safar Safarov</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Before starting up with the Subset Sum Problem, I would highly recommend you to read this introduction to <a href="https://medium.com/swlh/dynamic-programming-9a5e60fb7245"><strong>Dynamic Programming</strong></a>. Here I have covered the basic method on how to approach a DP based problem. We will be using the same concepts to solve the <strong>Subset Sum </strong>problem. I’d also recommend to go through the <a href="https://medium.com/@tanishqvyas069/dynamic-programming-0-1-knapsack-5af91763b6d5"><strong>Knapsack Problem</strong></a> since it’s the parent problem for <strong>Subset Sum Problem</strong>.</p><p>With that being said, let’s begin!</p><h3>1. What is Subset Sum Problem ?</h3><p>Given a set of <strong>N </strong>non-negative integers and a target sum <strong>S</strong>, determine if there exists a subset of the given set such that the sum of the elements of the subset equals to <strong>S</strong>. Return 1 if there exists such subset, otherwise return 0.</p><h3>2. Recursion, Memoization &amp; Tabulation</h3><p>This problem is very similar to the <a href="https://medium.com/@tanishqvyas069/dynamic-programming-0-1-knapsack-5af91763b6d5">0–1 Knapsack Problem</a>, which in this case is it’s parent problem. Thus I recommend you to have a look at the same.</p><p>If you’d have read the two, above mentioned articles, then you would know that in order to write a proper DP based solution one must be able to think of a recursive solution. We will be using Python3 for coding the solutions for this problem. So let’s see what a Recursive solution would be like.</p><h4>a) Recursive Approach</h4><p>In order to write a recursive solution, one must be able to figure out two things : <em>Base Condition &amp; Recursion Logic</em>/Recurrence Relation<em>.</em></p><ol><li><strong>Base Condition : </strong>The base condition always refers to the smallest possible case(s) for the problem we are trying to solve. In this case there are two possibilities :</li></ol><ul><li>If target sum <strong>S</strong> is equal to 0. In this case no matter what the given set is, one would always be able to find a subset (which is null set) such that some of the elements of that subset is 0.</li><li>If the number of elements in the set (<strong>N) </strong>is zero. In this case no matter how hard you we try, we won’t be able to get a subset such that the sum of elements is equal to target sum <strong>S</strong>. Thus in all these cases we return <strong>False</strong>. However if <strong>N = 0 </strong>as well as <strong>S = 0</strong>, we return <strong>True</strong> since the null set satisfies the requirements. But since we have already covered this case in last point, we need not worry about it here.</li></ul><p>2. <strong>Recursion Logic : </strong>Just like we did in <a href="https://medium.com/@tanishqvyas069/dynamic-programming-0-1-knapsack-5af91763b6d5">0–1 Knapsack Problem</a>, even here we see if there is a possibility of including the number in the subset or not.</p><ul><li>The value of the number must be less than or equal to the target sum <strong>B</strong> for it to be considered for inclusion.</li><li>If the number can be included, we consider two cases :</li></ul><ol><li>Inclusion of number : If the number is included then we reduce the target sum by the number and continue to next recursive call.</li></ol><pre>target_sum = target_sum - number</pre><p>2. Exclusion of number : If the number is not included then the target sum remains unchanged and we simply proceed to the next recursive call.</p><p>With all this in mind, this is how a recursive solution would look like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rDRXxPZ5Nd4Gs76yLNRnwQ.png" /></figure><p>With the basic logic and consideration of cases we discussed earlier, above is the proper recursive implementation of the same. Now that we have the recursive solution let’s convert this into a <strong>memoized</strong> solution.</p><h4>b) Memoization</h4><p>From our discussions in <a href="https://medium.com/swlh/dynamic-programming-9a5e60fb7245">this</a> and <a href="https://medium.com/@tanishqvyas069/dynamic-programming-0-1-knapsack-5af91763b6d5">this</a>, we all know that we must keep following points in mind while writing a memoized solution :</p><ul><li>In order to reduce the recursive calls, we save the computed values for later use. I prefer to call this variable <strong>store</strong>.</li><li>The dimensions of store depends on the number of changing parameters in our recursive solution. Which in this case is 2 : target sum &amp; N. Since target sum can take a total of <strong>S+1</strong> and number of elements can take a total of <strong>N+1</strong> possible values. Thus we have <strong>store[N+1][S+1]</strong>.</li><li>Before computing the answer for any call we check for the presence of answer in store. If it is present, we return the same. Otherwise we compute it and store it for later use.</li><li>The easiest way to visualize <strong>store</strong> is to understand the fact that (in this case)in general <strong>store[n][s]</strong> holds the answer for the function call <strong>isSubsetSum(number_set, n, s)</strong>.</li></ul><p>With these points in mind, let’s see how a modified solution would look like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uTR0ef8o1vbDGAvFpwcZ8g.png" /></figure><p>That’s how we would memoize our recursive solution with the addition of a few simple steps. This greatly improves the solution since it reduces the time complexity down to polynomial from exponential.</p><p>Now let’s see how one would approach to write a <strong>tabulated </strong>solution.</p><h4>c) Tabulation</h4><p>The key concept of tabluation is to be able to build the <strong>store</strong> from bottom to top with the help of <strong>base conditions</strong> and the <strong>recursive logic</strong>.</p><p>From our discussions in <a href="https://medium.com/swlh/dynamic-programming-9a5e60fb7245">this</a> and <a href="https://medium.com/@tanishqvyas069/dynamic-programming-0-1-knapsack-5af91763b6d5">this</a>, we all know that we must keep following points in mind while writing a tabulated solution :</p><ul><li>The dimensions of store depends on the number of changing parameters in our recursive solution. Which in this case is 2 : target sum &amp; N. Since target sum can take a total of <strong>S+1</strong> and number of elements can take a total of <strong>N+1</strong> possible values. Thus we have <strong>store[N+1][S+1]</strong>.</li><li>The easiest way to visualize <strong>store</strong> is to understand the fact that (in this case)in general <strong>store[n][s]</strong> holds the answer for the function call <strong>isSubsetSum(number_set, n, s)</strong>.</li><li>In order to get started, we must have something to build upon. Thus we need to initialize certain values of <strong>store</strong>. This is where the <strong>base conditions</strong> comes to the rescue. We initialize the store with the help of base conditions from the recursive solution.</li><li>The filling up of <strong>store</strong> is done using the initialized values and the recursion logic. Thus finally obtaining the value of <strong>store[n][targetSum] </strong>which as we know, holds the answer for the original function call <strong>isSubsetSum(number_set, n, targetSum)</strong>. Then we return the same.</li></ul><p>With these points in mind, let’s see what a Tabulated solution (bottom-up approach) would look like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jBI1xDyqmTIsk0t29YCJTA.png" /></figure><p>That’s how the tabulated solution can be written by following the previously discussed steps and our knowledge from recursive solution.</p><p>With this we have come to an end of <strong>Subset Sum Problem</strong>. I hope the article was informative and helped you to properly understand the concept of DP and what should be the approach for writing a <strong>memoized</strong> and <strong>tabulated </strong>solution for the <strong>Subset Sum Problem</strong>.</p><h3><strong>References &amp; other Articles</strong></h3><ol><li><a href="https://medium.com/swlh/dynamic-programming-9a5e60fb7245">Getting Started with Dynamic Programming</a></li><li><a href="https://medium.com/@tanishqvyas069/dynamic-programming-0-1-knapsack-5af91763b6d5">0–1 Knapsack Problem | Dynamic Programming</a></li><li><a href="https://tanishqvyas069.medium.com/dynamic-programming-equal-sum-partition-problem-b5059caf46bb">Equal Partition Problem | Dynamic Programming</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c386126621cd" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/dynamic-programming-subset-sum-c386126621cd">Dynamic Programming: Subset Sum</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[Dynamic Programming: 0–1 Knapsack]]></title>
            <link>https://tanishqvyas069.medium.com/dynamic-programming-0-1-knapsack-5af91763b6d5?source=rss-7132cd1d5ed0------2</link>
            <guid isPermaLink="false">https://medium.com/p/5af91763b6d5</guid>
            <category><![CDATA[dynamic-programming]]></category>
            <category><![CDATA[knapsack-problem]]></category>
            <category><![CDATA[memoization]]></category>
            <category><![CDATA[tabulation]]></category>
            <category><![CDATA[recursion]]></category>
            <dc:creator><![CDATA[Tanishq Vyas]]></dc:creator>
            <pubDate>Tue, 17 Nov 2020 09:40:19 GMT</pubDate>
            <atom:updated>2020-11-20T15:44:34.795Z</atom:updated>
            <content:encoded><![CDATA[<h4>Dynamic Programming Problem #1 : 0–1 Knapsack</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7TKen9T6MmNzl-WO" /><figcaption>Photo by <a href="https://unsplash.com/@emilep?utm_source=medium&amp;utm_medium=referral">Emile Perron</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Before starting up with the Knapsack Problem, I would highly recommend you to read this <a href="https://medium.com/@tanishqvyas069/dynamic-programming-9a5e60fb7245">introduction to Dynamic Programming</a>. Here I have covered the basic method on how to approach a DP based problem. We will be using the same concepts to solve the <strong>Knapsack</strong> problem.</p><p>With that being said let’s begin !</p><h3>What is 0–1 Knapsack ?</h3><p>The problem of 0–1 Knapsack goes something like this.</p><p>We are given an empty bag that can hold maximum of <strong>W</strong> weight. We have a set of <strong>N </strong>items. Each item has an associated value <strong>v</strong> and an associated weight <strong>w</strong>. Given these information, find the maximum profit you can make by carrying away as many items as you want, given that the sum of weights of the items does not exceed <strong>W</strong>.</p><p>So, for the sake of this example let’s assume :</p><p><strong>W = 10kg</strong></p><p><strong>N = 5</strong></p><p><strong>value = [2, 4, 6, 1, 9]</strong></p><p><strong>weight = [3, 2, 8, 7, 4]</strong></p><h3>Possible Approach</h3><p>Since the problem is more or less about inclusion or exclusion of an item from the entity set thus we can say that we should check all possible combinations of the items and see which one has the maximum value.</p><p>So, a pseudo code would be something like :</p><ul><li>Pick one item</li><li>See if it’s weight exceeds the current limit</li><li>if it does, then we do not include that item and move onto the next item</li><li>If it doesn’t then, we consider all the subsets where that item is included and where that item is excluded. Then we just simply return the one which has a higher value</li></ul><p>Seems a bit confusing right ? Let’s look at the code for better understanding.</p><h3>Recursive Approach</h3><p>Remember that we should always think of a Recursive approach first in order to make our work easier for thinking a DP based solution. The recursive code looks something like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fqHRjQ6_COvwGPe2Ow--yQ.png" /></figure><p>This would be a simple recursive solution for the 0–1 Knapsack Problem. But we all know that this isn’t the best possible way to solve it because of the issues that a recursive solution causes. Thus we move onto writing a memoized solution next using the same recursive code.</p><h3>Memoized Solution</h3><p>Let’s recall the key concepts that we need in order to build a memoized solution from a recursive solution.</p><ul><li>Store the computed values so that the next time the same call occurs, we won’t need to compute it again.</li><li>There are two changing parameters : <strong>W</strong> and <strong>N</strong>. Thus the <strong>store</strong> will be a two dimensional matrix.</li><li>Thus, <strong>store[N][W]</strong> will contain the answer for the function call <strong>knapsack(W, N, value, weight)</strong></li></ul><p>With these two rules in mind let’s see how a memoized solution looks like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*moMTDQnzU3MpfetULvCQ2A.png" /></figure><p>Thus with the help of <strong>store</strong> variable to store the computed values for later use, we are easily able to derive a memoized solution from the recursive solution. Now, let’s have a look at the Bottom-up approach for the same.</p><h3>Bottom-up Approach (Tabulation)</h3><p>We must remember that the key to writing the <strong>tabulated</strong> solution is having a proper understanding of the following points</p><ul><li><strong><em>store[N][W]</em></strong> : This holds the answer for the function call given by <strong>knapsack(W, N, value, weight)</strong></li><li>The dimensions of <strong><em>store</em></strong><em> </em>depends on the number of changing parameters. Which in this case are 2 : <strong>W </strong>and<strong> N</strong>.</li><li>We must have a relation between n-th computation and previous computation(s) so that we can build the <strong>store</strong> without actually having to call the function recursively.</li><li>The <strong>base condition </strong>of the recursive approach is used to initialize the <strong>store</strong> so that we can fill up the rest of it using the relation derived from recursive solution.</li></ul><p>With these points in mind, coding a <strong>tabulated</strong> solution is a piece of cake.</p><h4>1. Dimension of store</h4><p>Since values of <strong>W </strong>range from 0 to W and that of <strong>N</strong> range from 0 to N. Thus we have a total of <strong>W+1 * N+1</strong> possible combinations.</p><p>Thus the dimensions of <strong>store</strong> will be <strong>(N+1) x (W+1)</strong> or vice versa (as per our own implementation wish).</p><h4>2. Relation between entities</h4><p>While writing these relations we must keep in mind that <strong>store[N][W]</strong> is same as <strong>knapsack(W, N, value, weight) </strong>since that’s how we have mapped them.</p><ul><li><strong>Inclusion Case : </strong>When the item is included then the value of the current function call <strong>knapsack(W, N, value, weight) </strong>is same as</li></ul><p><strong>max(knapsack(W, N-1, value, weight), knapsack(W-weight[N-1], N-1, value, weight))</strong></p><p>Where we take the max of inclusion and exclusion case.</p><ul><li><strong>Exclusion Case : </strong>When the item isn’t included the value of the current function call <strong>knapsack(W, N, value, weight) </strong>is same as the function call <strong>knapsack(W, N-1, value, weight)</strong></li></ul><h4>3. Initializing the Store</h4><p>We must keep in mind that the <strong>store</strong> is initialized using the logic of base condition from the recursive solution. Thus all the entries where either of the index is 0 (i.e. either W = 0 or N = 0), the value of <strong>store[w][n] will also be equal to 0</strong>.</p><p>Now that we have all the basic ideas needed for Tabulated solution, let’s see how the coded solution looks like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p_u_yjwiR7eScBh7iBDDlA.png" /></figure><p>That’s how we can derive a tabulated solution with a few points in mind and the proper recursive solution.</p><p>With this we have come to an end of <strong>0–1 Knapsack Problem</strong>. I hope the article was informative and helped you to properly understand the concept of DP and what should be the approach for writing a <strong>memoized</strong> and <strong>tabulated </strong>solution for <strong>0–1 Knapsack Problem</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5af91763b6d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic Programming]]></title>
            <link>https://medium.com/swlh/dynamic-programming-9a5e60fb7245?source=rss-7132cd1d5ed0------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a5e60fb7245</guid>
            <category><![CDATA[bottom-up]]></category>
            <category><![CDATA[dynamic-programming]]></category>
            <category><![CDATA[memoization]]></category>
            <category><![CDATA[tabulation]]></category>
            <category><![CDATA[python3]]></category>
            <dc:creator><![CDATA[Tanishq Vyas]]></dc:creator>
            <pubDate>Tue, 17 Nov 2020 08:24:20 GMT</pubDate>
            <atom:updated>2021-03-21T18:17:12.371Z</atom:updated>
            <content:encoded><![CDATA[<h4>Getting started with Dynamic Programming</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZLAp-Go1HEFQK-_l" /><figcaption>Photo by <a href="https://unsplash.com/@emilep?utm_source=medium&amp;utm_medium=referral">Emile Perron</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>1. What is Dynamic Programming ?</h3><p>In simple words, one can say that it is an optimization over plain recursion technique. This is achieved by reducing the number of recursive calls, either by storing the intermediate computed values or by deriving the final computation based on some kind of logical relation. This ultimately leads to reduced time complexities (from exponential to polynomial), thereby improving the overall performance of the solution.</p><p>Since it’s a programming paradigm thus it has nothing to do with being specific to a particular language or set of programming languages.</p><p>With that being said let’s dive into <strong>Dynamic Programming</strong>.</p><h3>2. Recursion, Tabulation &amp; Memoization</h3><p>The key to understanding any problem’s solution that employs Dynamic Programming (commonly referred to as <strong>DP</strong>), is Recursion. One must first master the skill to code a recursive solution for the same problem. Building a DP-based solution using either <strong>Tabulation</strong> or <strong>Memoization</strong> can then be very easily done with the help of the recursive code.</p><p>For this article, we will be taking an example of <strong>Fibonacci Numbers </strong>and implement the solution in <strong>Python3</strong>. A very nice video resource for the same would be <a href="https://youtu.be/vYquumk4nWw">this</a>. Although I recommend finishing the read since we will be discussing a bit more and different things.</p><p>The <strong><em>Fibonacci series</em></strong><em> </em>is a series of numbers where each number follows the following rule :</p><p>Number (i) = Number (i-1) + Number (i-2)</p><p>Thus in order to start the series, the first two terms are taken as 0 and 1.</p><p>Therefore the Fibonacci series looks something like this</p><p>0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ……..</p><h4>a) Recursive Approach :</h4><p>In order to write a recursive solution, one must be able to figure out two things: <em>Base Condition &amp; Recursion Logic</em>/Recurrence Relation<em>.</em></p><ol><li><strong>Base Condition: </strong>The base condition always refers to the smallest possible case(s) for the problem we are trying to solve. In this case, there are two possibilities :</li></ol><ul><li>When the recursive call is for the <strong>first Fibonacci</strong> number i.e. <strong>n = 1</strong>, thus we return the first Fibonacci number <strong>0</strong>.</li><li>When the recursive call is for the <strong>second Fibonacci</strong> number i.e. <strong>n = 2</strong>, thus we return the first Fibonacci number <strong>1</strong>.</li></ul><p>2. <strong>Recursion Logic: </strong>Just like we discussed above, according to the definition of the Fibonacci Series the n-th Fibonacci number is simply the sum of (n-1)-th and (n-2)-th Fibonacci numbers respectively.</p><p>With all this in mind, this is how a recursive solution would look like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*gsjpwOOyFw1ddCFGr3NYQA.png" /></figure><p>Here the function<strong> <em>fibonacci(n)</em></strong> returns the nth Fibonacci number. Just in case if anyone’s wondering about where to get such a neat code presentation, it&#39;s right <a href="https://carbon.now.sh/">here</a>.</p><p>Simple isn’t it? So what’s the problem that makes us look for DP-based approaches for the same?</p><ul><li>Possibility of Stackoverflow upon calling the function for larger inputs</li><li>Increased computation due to repetitive computation of values for the same input</li></ul><p>Thus we opt for alternate approaches based on Dynamic Programming.</p><h4><strong>b) Memoization ( Top-Down Approach)</strong></h4><p>The idea of memoization is very simple. We faced the issue of repetitive computation in the recursive solution, so why not store the computed values and reuse them instead of computing them again?</p><p>We make use of an appropriate Data Structure in order to store the computed values. Thus reducing the amount of computation time. I prefer to call this storage variable(the variable that represents the data structure) a <strong>store</strong>.</p><p>We must keep the following points in mind while writing a memoized solution :</p><ul><li>In order to reduce the recursive calls, we save the computed values for later use. I prefer to call this variable <strong>store</strong>.</li><li>The dimensions of the <strong>store</strong> depend on the number of changing parameters in our recursive calls. Which in this case is 1: N. Since <strong>N</strong> can take a total of N values (from 1— N) thus the dimensions will be <strong>store[N]</strong>. I have assumed that the array begins from 1 in the code that follows thus taken the dimensions as N+1 while declaration.</li><li>Before computing the answer for any call we check for the presence of an answer in the <strong>store</strong>. If it is present, we return the same. Otherwise, we compute it and store it for later use.</li><li>The easiest way to visualize a <strong>store</strong> is to understand the fact that in general <strong>store[n]</strong> holds the answer for the function call <strong>fibonacci(n)</strong>. In other words, we can say that <strong>store </strong>holds the answer to the respective function call for the changing parameters/arguments. Eg: In this case <strong>store[7]</strong> will hold the answer for <strong>fibonacci(7)</strong> and so on.</li></ul><p>With these points in mind, let’s see how a modified solution would look like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*F2KBIWSJ9cdIolj7hj8kvQ.png" /></figure><p>We make use of the <strong>store</strong> list in order to save the computed values. Every time there is a function call, instead of directly computing, we first check if the value is present in <strong>store </strong>or not. If it is present then we return the same, otherwise, we compute the value and store it for later use. Thus simple memoization technique helps in reducing the overall repetitive recursive calls.</p><p>So what’s the issue with this approach? Even though it does reduce the time complexity from exponential to polynomial but there is still a possibility of stack overflow for very large inputs. Thus we make use of <strong>Tabulation</strong> in order to completely eliminate the use of recursive calls.</p><h4>c) Tabulation (Bottom-up Approach)</h4><p>The <strong>tabulation</strong> approach deals with the above-mentioned issue by totally removing the need for any recursive call.</p><p>If we notice properly then each n-th number’s computation depends on some previous number (a smaller version of the same problem). Thus the basic idea is to make use of the recursive code to be able to write the tabulation (bottom-up) code.</p><ul><li><strong><em>Base Condition: </em></strong>The base condition in the recursive code is used in order to initialize the <strong>store</strong> list with some values.</li><li><strong><em>Recursive Calls: </em></strong>This gives us the relation between n-th computation and previous computations.</li></ul><p>Thus all we need to do is write the proper recursive solution, then we can easily derive the <strong>memoized </strong>and<strong> tabulated</strong> solutions.</p><h4>How to interpret Store?</h4><p>In easy terms, one can say that <strong>store[i]</strong> stores the answer for <strong>fibonacci(i)</strong>. Thus if we call <strong>fibonacci(6)</strong>, then we just have to compute <strong>store[6]</strong>. (Assuming that the array begins from 1).</p><p>So here’s how the tabulated solution will look like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1fw52710-zW5b17VO4s5GQ.png" /></figure><p>Thus with the help of the recursive code, we can easily derive the tabulated code by keeping very simple rules in mind :</p><ul><li>Using the Base Condition to initialize the store</li><li>Using the Recursive Code to Derive the Relation for filling up the Store</li><li>Function(n) — &gt; store[n] (or store[n-1] if we use 0 indexing)</li><li>The dimension of the <strong>store</strong> is given by the changing parameters in the function call. Since in our recursive function calls the only value that changed was <strong>n</strong> thus store for this problem will be 1-D. It can be 2-D if there are two changing parameters.</li></ul><p>With this, we come to an end of an introduction to <strong>Dynamic Programming</strong>. I hope the article helped you to properly understand the concept of DP and what should be the approach for writing a <strong>memoized</strong> and <strong>tabulated </strong>solution.</p><h4>What Next?</h4><ul><li><a href="https://tanishqvyas069.medium.com/dynamic-programming-0-1-knapsack-5af91763b6d5">0–1 Knapsack | Dynamic Programming</a></li><li><a href="https://tanishqvyas069.medium.com/dynamic-programming-subset-sum-c386126621cd">Subset Sum Problem | Dynamic Programming</a></li><li><a href="https://tanishqvyas069.medium.com/dynamic-programming-equal-sum-partition-problem-b5059caf46bb">Equal Sum Partition Problem | Dynamic Programming</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a5e60fb7245" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/dynamic-programming-9a5e60fb7245">Dynamic Programming</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[Standard Template Library (STL) in C++ | Maps]]></title>
            <link>https://levelup.gitconnected.com/standard-template-library-stl-in-c-maps-346c30fdf487?source=rss-7132cd1d5ed0------2</link>
            <guid isPermaLink="false">https://medium.com/p/346c30fdf487</guid>
            <category><![CDATA[stl]]></category>
            <category><![CDATA[c-plus-plus-language]]></category>
            <category><![CDATA[cplusplus]]></category>
            <category><![CDATA[maps-in-stl]]></category>
            <category><![CDATA[standard-template-library]]></category>
            <dc:creator><![CDATA[Tanishq Vyas]]></dc:creator>
            <pubDate>Sun, 21 Jun 2020 09:54:11 GMT</pubDate>
            <atom:updated>2020-06-21T09:54:11.430Z</atom:updated>
            <content:encoded><![CDATA[<h4>Getting started with STL in C++</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jbAqfKdHYf7xv2C-" /><figcaption>Photo by <a href="https://unsplash.com/@ffstop?utm_source=medium&amp;utm_medium=referral">Fotis Fotopoulos</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What are Maps in STL ?</h3><p>Maps are nothing but a type of associative container which stores elements in the form of key-value pairs. For those of you who are familiar with python, you can think of maps like a dictionary in python.</p><p>A <strong>key</strong> in map is used to uniquely identify the element and the <strong>value</strong> contains the corresponding stored data. Thus a key has to be unique and cannot repeat but the values can be same for two different keys.</p><p>Eg :</p><p>Enrolment Number : Name</p><p>Here <strong>Enrolment Number </strong>is the key and <strong>Name</strong> is the corresponding value. The data type of the key and value may or may not be the same. Thus <strong>Enrolment Number </strong>cannot repeat but the <strong>Name</strong> can.</p><p>The elements are stored within the container in a sorted fashion based on the key. With that being said let’s have look at the syntax of maps.</p><h3>Syntax</h3><p>In order to make use of maps in C++ one needs to include the <strong>&lt;map&gt;</strong> header.</p><pre>#include &lt;map&gt;</pre><p>Now, let’s initialise a map</p><p><strong>Syntax : map &lt;data-type-of-key, data-type-of-value&gt; mapName;</strong></p><p>Eg : map &lt;int, string&gt; studentList;</p><h3>Initialising and adding elements</h3><pre>#include&lt;iostream&gt;<br>#include&lt;map&gt;</pre><pre>using namespace std;</pre><pre>int main()<br>{</pre><pre>    map &lt;int, string&gt; studentList;</pre><pre>    // Adding values directly<br>    studentList[1] = &quot;John Doe&quot;;</pre><pre>    // Adding elements using make_pair()<br>    studentList.insert(std::make_pair(2, &quot;Carl Max&quot;));</pre><pre>    // Adding using insert alone<br>    studentList.insert({3, &quot;Rachel&quot;});</pre><pre>    // Overwriting an existing element<br>    studentList[1] = &quot;John Carter&quot;;</pre><pre>    return 0;</pre><pre>}</pre><p>By default the map is ordered with respect to the keys in ascending order but one can specify the order in which we want the elements to be stored while declaring the map.</p><p><strong>Syntax : map &lt;data-type-of-key , data-type-of-value, greater &lt;data-type-of-key&gt;&gt; mapName;</strong></p><pre>// Ascending order<br>map &lt;int, string&gt; studentList;</pre><pre>// Descending order<br>map &lt;int, string, greater&lt;int&gt; &gt; studentList;</pre><h3>Accessing the elements</h3><p>The elements can be accessed directly if we know the key</p><pre>cout &lt;&lt; studentList[1]&lt;&lt;&quot;\n&quot;;</pre><p>Iterating through the map</p><pre>for(auto &amp;it: studentList)<br>{<br>     cout&lt;&lt;&quot;Key : &quot;&lt;&lt; it.first &lt;&lt;&quot; ; Value : &quot;&lt;&lt; it.second&lt;&lt;&quot;\n&quot;;<br>}</pre><p><strong>Output:</strong></p><p>Key : 1 ; Value : John Carter<br>Key : 2 ; Value : Carl Max</p><p><strong>Note : </strong>The <strong>iterator.first </strong>helps us to access the <strong>key</strong> while <strong>iterator.second</strong> helps us to access the <strong>value</strong> of the element the iterator is pointing to. The printed order is ascending but one can always change the way they want to store the elements by changing the declaration .</p><p>You can read more about iterator and corresponding functions <a href="https://medium.com/@tanishqvyas069/standard-template-library-stl-in-c-iterators-63baeab7959f">here</a>.</p><p>All the iterator functions remains the same for maps as well as they were for vectors and lists. You can read up more on those over <a href="https://www.cplusplus.com/reference/map/map/map/">here</a>.</p><h3>Finding the elements</h3><p>In order to get the iterator to an element which is present in the container we make use of <strong><em>find()</em></strong><em> function.</em></p><p>It accepts only one input parameter which is the key to be searched for and returns an iterator pointing to that element. In case the key isn’t present then it returns <strong>map.end()</strong></p><pre>auto itr1 = studentList.find(22);</pre><pre>if( itr1 != studentList.end())<br>{<br>    cout&lt;&lt;&quot;element is present&quot;;<br>}<br>else<br>{<br>cout&lt;&lt;&quot;element isn&#39;t present&quot;;<br>}</pre><pre>// Assuming there is no key 22 in the map</pre><pre><strong>Output:</strong></pre><pre>element isn&#39;t present</pre><p>Now that we have an understanding of how to use find function let’s see how remove elements from a map.</p><h3>Removing the elements</h3><ul><li><strong>Removing the elements with the help of keys</strong></li></ul><pre>studentList.erase(2);   // Remove the element corresponding to key 2</pre><ul><li><strong>Removing elements using iterators</strong></li></ul><pre>// function to erase given position</pre><pre><strong>auto</strong> it = studentList.find(2);</pre><pre>studentList.erase(it);</pre><ul><li><strong>Removing elements which fall in a certain range</strong></li></ul><p><strong>Syntax :</strong> map_name.erase(iterator position 1, iterator position 2)</p><pre><strong>auto</strong> it1 = studentList.find(20);</pre><pre><strong>auto</strong> it2 = studentList.find(50);</pre><pre>studentList.erase(it1, it2);</pre><p>This removes all the elements in the range 20 – 50 with element corresponding to 20 included but not 50.</p><p>With that gentle introduction lets quickly build a small snippet of code that prints out the subject marks of students. Here we will assume that the names are unique for each student.</p><h3>Example</h3><p>Let’s initialise our map first where the keys will be student name and the value will be a vector of marks. To keep it small we will consider marks for only three subjects. Also we want it to be ordered in descending order with respect to names</p><pre>#include &lt;iostream&gt;<br>#include &lt;map&gt;<br>#include &lt;vector&gt;</pre><pre>using namespace std;</pre><pre>int main()<br>{<br>    map &lt;string, vector &lt;float&gt;, greater&lt;string&gt;&gt; grades;</pre><pre>    return 0;<br>}</pre><p>Now let’s add the marks of students into the map. We will do it for 3 students in our example.</p><pre>// Entering marks for Ronald<br>grades[&quot;Ronald&quot;].push_back(63);<br>grades[&quot;Ronald&quot;].push_back(79);<br>grades[&quot;Ronald&quot;].push_back(94);</pre><pre>// Entering marks for Harry<br>grades[&quot;Harry&quot;].push_back(70);<br>grades[&quot;Harry&quot;].push_back(65);<br>grades[&quot;Harry&quot;].push_back(88);</pre><pre>// Entering marks for Hermione<br>grades[&quot;Hermione&quot;].push_back(93);<br>grades[&quot;Hermione&quot;].push_back(98);<br>grades[&quot;Hermione&quot;].push_back(90);</pre><p>Now let’s print all their marks i.e. the contents of the map</p><pre>for(auto &amp;ele: grades)<br>{<br>     cout&lt;&lt;&quot;Name : &quot;&lt;&lt; ele.first&lt;&lt;&quot;\n&quot;;</pre><pre>     for(auto &amp;marks: ele.second)<br>     {<br>        cout&lt;&lt;marks&lt;&lt; &quot; &quot;;<br>     }<br>     cout&lt;&lt;&quot;\n\n&quot;;<br>}</pre><p>Note that the vector itself is a container we need to iterate over in order to get the data of each student.</p><p><strong>Output:</strong></p><pre>Name : Ronald<br>63 79 94</pre><pre>Name : Hermione<br>93 98 90</pre><pre>Name : Harry<br>70 65 88</pre><p>With the completion of this example we are done with an introduction to <strong>Map </strong>container in C++. It is a really useful container which is used replicate the functionality of associative arrays.</p><p>We will be exploring other containers in upcoming articles till then keep learning : )</p><h3>Other References</h3><ul><li><a href="https://medium.com/@tanishqvyas069/standard-template-library-stl-in-c-iterators-63baeab7959f">Iterators in C++</a></li><li><a href="https://www.cplusplus.com/reference/map/map/">Maps</a></li><li><a href="https://medium.com/swlh/standard-template-library-stl-in-c-vectors-b5436b35492d">Vectors in C++</a></li><li><a href="https://medium.com/@tanishqvyas069/standard-template-library-stl-in-c-lists-201f42cb8f3d">Lists in C++</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=346c30fdf487" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/standard-template-library-stl-in-c-maps-346c30fdf487">Standard Template Library (STL) in C++ | Maps</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[Standard Template Library (STL) in C++ | Lists]]></title>
            <link>https://medium.com/swlh/standard-template-library-stl-in-c-lists-201f42cb8f3d?source=rss-7132cd1d5ed0------2</link>
            <guid isPermaLink="false">https://medium.com/p/201f42cb8f3d</guid>
            <category><![CDATA[standard-template-library]]></category>
            <category><![CDATA[lists-in-cplusplus]]></category>
            <category><![CDATA[stl]]></category>
            <category><![CDATA[c-plus-plus-language]]></category>
            <category><![CDATA[cplusplus]]></category>
            <dc:creator><![CDATA[Tanishq Vyas]]></dc:creator>
            <pubDate>Fri, 19 Jun 2020 07:48:44 GMT</pubDate>
            <atom:updated>2020-06-23T09:15:41.357Z</atom:updated>
            <content:encoded><![CDATA[<h4>Getting started with STL in C++</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MnbbOSGVAO1skbD5" /><figcaption>Photo by <a href="https://unsplash.com/@clemhlrdt?utm_source=medium&amp;utm_medium=referral">Clément H</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The <strong>Standard Template Library (STL) </strong>is a very useful set of template classes containing various containers. One among these containers is <strong>Lists</strong>. Today we’ll be having a look at <strong>Lists</strong> in <strong>STL</strong>. But before we proceed further I’d like to say that if this is your first time learning STL then I’d recommend you have a look at <a href="https://medium.com/@tanishqvyas069/standard-template-library-stl-in-c-vectors-b5436b35492d">this article</a> before beginning with this one.</p><p>With that being said let’s dive further into the topic by knowing what are lists in STL ?</p><h3><strong>A. Lists in STL</strong></h3><p>Lists are a type of sequence containers which provides us with constant insertion and deletion time anywhere within the sequence given that we have obtained the corresponding iterator to the same. It also allows us traversal in both the directions.</p><p>List containers are implemented as doubly-linked lists. The memory management is done internally by maintaining a link to the previous as well as the next element in the sequence with respect to each element. A significant drawback of lists being that we don’t have direct access to the elements since it uses non contiguous memory allocation for each element in the sequence. Thus in order to get to a specific element in the sequence one has to iterate through the list which takes linear time. Apart from that it also takes up a bit more extra space when compared to vectors, which it uses to keep track of the links to previous and next elements corresponding to each element in the sequence.</p><h3><strong>B. Syntax and Functions</strong></h3><p>One should make sure to import the corresponding list header before making use of lists in C++</p><pre>#include &lt;list&gt;</pre><p>Lists allow direct insertion and deletion at the beginning as well as the end unlike vectors which allow insertion and deletion only at the end.</p><p>This is how we declare a list container in C++</p><p><strong>Syntax : list &lt;data-type&gt; myList;</strong></p><p>Eg : list &lt;int&gt; myList;</p><pre>#include &lt;iostream&gt;<br>#include &lt;list&gt;</pre><pre>using namespace std;</pre><pre><strong>int</strong> main()</pre><pre>{</pre><pre>list &lt;<strong>int</strong>&gt; l;            // Initialize an empty list<br>l.assign(4, 49);         // Assigning 4 elements with value 49</pre><pre>list &lt;<strong>int</strong>&gt; l1(5, 33);    // 5 elements with 33 as their value</pre><pre><strong>return</strong> 0;</pre><pre>}</pre><p>One thing to keep in mind is that functions like</p><p><strong><em>assign(), begin(), end(), empty(), size(), front(), back(), </em></strong><em>etc are all same when it comes to usage for all the containers. A list of which can be found </em><a href="https://www.cplusplus.com/"><em>here</em></a><em>.</em></p><p>The iterator functions, capacity functions, element access functions, basic modifiers, etc are all the same for all the containers. Thus we need to learn them only once rather than learning them over and over again for each container.</p><p>Lists although provides us with two more modifier functions than vectors</p><ul><li><strong><em>push_front(): </em></strong><em>This function is used in order to add an element at the beginning of the sequence.</em></li><li><strong><em>pop_front():</em></strong><em> This function is used in order to remove an element from the beginning of the sequence.</em></li></ul><p><strong>Now, let’s have a look on how to iterate through the elements and access the elements in the list</strong></p><p>Let us begin with creating a list first</p><pre>list &lt;int&gt; myList;</pre><pre>myList.push_front(20);<br>myList.push_front(10);<br>myList.push_back(30);</pre><pre>// We should have elements in the order<br>// 10 20 30</pre><p>Now let’s create a function to display the list</p><pre>void printlist(list &lt;int&gt; l)<br>{</pre><pre>  // Initialize an iterator</pre><pre>  list &lt;<strong>int</strong>&gt; :: iterator it = l.begin();</pre><pre>  for(it; it != l.end(); it++) <br>  {</pre><pre>     cout&lt;&lt;*it&lt;&lt;” ”;</pre><pre>  } // end for loop</pre><pre>  cout&lt;&lt;”\n”;</pre><pre>  return;</pre><pre>}</pre><p>Let’s call this function to print our list.</p><pre>printlist(myList);</pre><pre><strong>Output:<br></strong>10 20 30</pre><p>That’s how we can iterate through our list. Now let’s see how can we insert an element in the list. Say we want to insert 25 after 20 and before 30</p><pre>list &lt;int&gt; :: iterator it = myList.begin();<br>for(it; it != myList.end(); it++)<br>{<br>    if(*it == 30)<br>    {<br>        myList.insert(it, 25);</pre><pre>    }<br>}</pre><p>Voila !</p><p>We have inserted an element at desired location in our list. With that we have come to an end of this article. I hope you found it useful.</p><p>Lists are a lot similar to vectors with only a few differences. The extensive use of vectors and lists helps us to extract a lot out of C++. One must always keep in mind that this article was a gentle introduction to get all of you familiar with lists in C++. We will have a look at other containers in upcoming articles. Till then keep learning : )</p><h3><strong>References</strong></h3><ul><li><a href="http://www.cplusplus.com/reference/list/list/list/"><em>cplusplus.com</em></a></li><li><a href="https://medium.com/@tanishqvyas069/standard-template-library-stl-in-c-iterators-63baeab7959f">Iterators in C++</a></li><li><a href="https://medium.com/@tanishqvyas069/standard-template-library-stl-in-c-vectors-b5436b35492d">Getting started with STL | Vectors</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=201f42cb8f3d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/standard-template-library-stl-in-c-lists-201f42cb8f3d">Standard Template Library (STL) in C++ | 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>
    </channel>
</rss>