<?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 Harsh Joshi on Medium]]></title>
        <description><![CDATA[Stories by Harsh Joshi on Medium]]></description>
        <link>https://medium.com/@josharsh?source=rss-7eb0d82fcb38------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*ZZn40u7Jilg-i9U80vngCA.jpeg</url>
            <title>Stories by Harsh Joshi on Medium</title>
            <link>https://medium.com/@josharsh?source=rss-7eb0d82fcb38------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 00:44:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@josharsh/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[Can you make Javascript more powerful?]]></title>
            <link>https://josharsh.medium.com/can-you-make-javascript-more-powerful-1b693f301d14?source=rss-7eb0d82fcb38------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b693f301d14</guid>
            <category><![CDATA[dev]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Harsh Joshi]]></dc:creator>
            <pubDate>Mon, 26 Jul 2021 12:26:04 GMT</pubDate>
            <atom:updated>2021-07-26T12:26:04.229Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>“ Do you know the most powerful thing about Javascript? Spoiler Alert, It is not asynchronicity, first-class citizen principles, not even my favorite, closures. While all of these make javascript a delight, what makes javascript powerful is not focusing on attaining power. Javascript is not power-hungry by design.”</blockquote><p>Javascript in its vanilla form does not intend to provide you with capabilities touching skies and jumping oceans. That is where the amazing dev community along with packages breaks into the scene, bringing in powers from dark dimensions, Human Batteries, Arc Reactor, and who knows where else.</p><p>Yes, I exaggerated. Now that I have your attention, let’s dive deep into the perspective this blog aims to set. The core parts of javascript, widely popular and used, are not its own. That still does not take away the joy of working with it and It is still technically javascript.</p><p>This blog tries to answer its own title with a big Yes. It sets to establish “<em>building for public “patterns</em> while talking about javascript, modules and publishing to npm. If you are still reading this blog, I assume you are familiar with what npm is. The exciting part of working in javascript (like many other languages) is the ability to share your work with others in a manner that they might use your work in their projects. Let’s begin with going over the basics of publishing your own module to npm, and then how to make use of that in a project.</p><h3>Pilot: Getting hands dirty!</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.slideshare.net%2Fslideshow%2Fembed_code%2Fkey%2FkeNdakBp9TvCtn&amp;display_name=SlideShare&amp;url=https%3A%2F%2Fwww.slideshare.net%2FHarshJoshi107%2Fwriting-a-npm-module&amp;image=https%3A%2F%2Fcdn.slidesharecdn.com%2Fss_thumbnails%2Fwritinganpmmodule-210723191510-thumbnail-4.jpg%3Fcb%3D1627068029&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=slideshare" width="600" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f4897358a2d0ea264d5bc92d390d458/href">https://medium.com/media/3f4897358a2d0ea264d5bc92d390d458/href</a></iframe><p>That might have been fairly easy. If you see something not right there, it’s only because you figured it out ;)</p><p>A fun way to get started is by thinking small and smart. Before you begin writing your own modules, a good read would be how modules work in javascript, especially post ES6. You can find one <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules">here</a>.</p><h3>Episode 2: The Code Isomer Conundrum</h3><p>Code isomers are two or more pieces of code that do the same work but differ in the way they are written. (Yes, I just made that up but it doesn’t make it any less relevant)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/0*jIZUn1_E-2xrJNaQ" /></figure><p>This is the most fundamental example of it. When writing code that delivers much bigger the style developers use takes the shape of patterns. When writing modules that are intended for public use, a well-defined pattern reduces the headache of the person consuming that module. These patterns are categorically closer to the purpose of being used by anyone, anywhere and anytime than the language hence I call them “building for public patterns”.</p><blockquote>Have you ever come across a cool npm package, the intention of which gave you a tickle, but the implementation could not? When you installed the package you could not really understand what does what, there was no documentation readily available and you ultimately had to drop it? Yes, it does not happen when Facebook releases react.js or any organization releases a big package. But out there are many developers working on pretty cool stuff, some of which unfortunately fails to abide by the rather misty de facto standards of releasing to the public. These misty de facto standards are what we introduce here as <em>building for public patterns</em>.</blockquote><p>There are two schools of thought on how to write code in any language. The first school of thought is that it should be written in a manner that is easily understood by the person who wrote it. The second school of thought is that it should be written in a fashion that is easily understood by the person who reads it.</p><p>The first school of thought is more often linked to the phrase “write self-documenting code” and is often referred to as “write-what-you-know” or “write-what-you-need”. Regardless, it is a very common factor in programming, and it is often a necessity to write code this way when a project is small and the time of writing the code outweighs the time of reading it.</p><p>The second school of thought is a little closer to what we just introduced as <em>“building for public patterns”</em> and is often linked to the phrase “write clean code” and also called “write-what-you-need-to-know”. It is also common to write code to be read by others. A programmer who is writing code that will be read by other programmers will write the code in a manner that is easily understood by the one who reads it. This is especially true when the code is in a highly complex area of the program.</p><p><em>“Building for public”</em> patterns somewhere introduce a new school of thought that is closer to the person consuming the code and not does not care much about how the actual code is written. In javascript, the concept of modules post ES6 pretty much standardizes this notion. However, much is still left on the developer to abide by. This includes naming the handlers, exporting, shaping the module, and much more. It also goes on further to include optimizing the size of the module, adding more weight to the “consumer-first” approach of publishing your work.</p><p>Let’s assume you are sick of the native console API and you have promised yourself that you won’t use <em>console.log()</em> again. You decide to write your own function which uses an API you build to send logs to your phone.</p><pre>const unConsoleLog = (data) =&gt; {<br></pre><pre>    fetch(API_URL, {</pre><pre>            method: &#39;POST&#39;,</pre><pre>            headers: {</pre><pre>                &#39;Content-Type&#39;: &#39;application/json&#39;,</pre><pre>                &#39;token&#39;: &#39;XXXX-XXX-XXX-XXXXX&#39;,</pre><pre>            },</pre><pre>            body: JSON.stringify(data),</pre><pre>        })</pre><pre>        .then(response =&gt; response.json())</pre><pre>        .then(data =&gt; {</pre><pre>            console.log(&#39;Success:&#39;, data);</pre><pre>        })</pre><pre>        .catch((error) =&gt; {</pre><pre>            console.error(&#39;Error:&#39;, error);</pre><pre>        });<br></pre><pre>}</pre><p>The idea becomes so exciting that you now want to make it accessible for public use. You decide to release this as an npm module.</p><p>Can you think of the best possible way to release this to the public using <em>“Building for Public”?</em></p><p><em>to be completed…</em></p><p>Next on “Can you make JS more powerful?”</p><ul><li>Consumer First principles in “<em>Building for public”</em> patterns.</li><li>Encapsulation in JS and life before ES6</li><li>“For and by the public” with open-source</li><li>Making javascript powerful with your first module. (&lt;First&gt;.js)</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b693f301d14" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Approaches to Serverless Deployment]]></title>
            <link>https://josharsh.medium.com/approaches-to-serverless-deployment-cea55f8d2c8d?source=rss-7eb0d82fcb38------2</link>
            <guid isPermaLink="false">https://medium.com/p/cea55f8d2c8d</guid>
            <dc:creator><![CDATA[Harsh Joshi]]></dc:creator>
            <pubDate>Sun, 23 May 2021 15:08:50 GMT</pubDate>
            <atom:updated>2021-05-23T15:08:50.858Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deployment in a Serverless Environment</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*c6SI20uEF_dmhunK" /></figure><p>Yes, Serverless is cool. It is one less thing to do, but there’s certainly more to it. When you are not occupied with tedious, time-consuming server development, operations, and maintenance, you can take some time out to click some heads in your favorite multiplayer first-person shooter game or even learn to make Pepperoni Pasta.</p><p>Especially when you are building a startup, you want to be efficient in solving bigger problems at hand. There are many other factors teams consider before moving to the serverless paradigm. Once you have taken the call, you are presented with multiple strategies for deployment.</p><blockquote>This blog helps you explore more about approaches and suggests to you the paradigm that might fit your strategies. This blog will consider Google cloud platform for most of the examples and explanations but the deployment strategies more or less remain similar among all the major cloud vendors.</blockquote><p>Serverless computing is a method of providing back-end services on an as-used basis. A serverless provider allows users to write and deploy code without the hassle of worrying about the underlying infrastructure. Precisely back end as a managed service sums up the essence of the serverless paradigm. You write code as functions, ship it to a third party. The third-party is responsible for managing the entire infrastructure which hosts your code. You are given a window through which you and the rest of the world can interact with the code. While the management is done by the third party, it must be realized that you are the one in control of your code.</p><p>Serverless computing allows developers to purchase back-end services on a flexible ‘pay-as-you-go’ basis, meaning that developers only have to pay for the services they use. This is like switching from a cell phone data plan with a monthly fixed limit, to one that only charges for each byte of data that actually gets used.</p><p>One of the most commonly used serverless entities is the cloud functions. Google Cloud defines cloud functions as a serverless execution environment for building and connecting with cloud services. Cloud functions expose you to write simple single-purpose functions that are attached to events emitted from Cloud infrastructure and services the code executes in a fully managed environment.</p><p>To put things into perspective once you have the service architecture up and running you will need to package your updated code and give it to a provider. This way the management completely becomes the responsibility of the third-party vendor, this also means that the third-party cloud vendor is responsible for updating the code and making it accessible to all the future requests that come. However, you are in charge of having a mechanism to push the updated code from your source repositories to the cloud vendor. Each function is associated with its own environment and the update won’t affect any code during execution. The old functions generally die after the completion and the update will seem to be instantaneous.</p><p>GCP Says, <em>“Google Cloud Functions is a serverless execution environment for building and connecting cloud services. With Cloud Functions, you write simple, single-purpose functions that are attached to events emitted from your cloud infrastructure and services. Your function is triggered when an event being watched is fired. Your code executes in a fully managed environment”</em></p><blockquote>That’s comforting right? Or is it alarming. It is a topic for future reveals when we talk about observability in managed services.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/0*rTKvHgzN53JIdhj0" /></figure><p>It is quite obvious that to use the serverless architecture you need to handle your deployments in a different way, most likely you might consider having continuous integration and a continuous delivery pipeline. The delivery pipeline usually begins after the development is completed but it is as important. Most of the cloud vendors today give you access to entities like cloud functions directly from the console, which might not be a good idea. Using serverless architecture you are already dependent on the third-party vendors for managing resources, and using the console to create cloud functions without having a copy of the source code might be a bad idea.</p><p>Deployment Options: Deployments work by shipping your function’s source code to a place in cloud storage. There are a number of ways the deployments can be done. Typically cloud Functions run with container orchestration. In simple words, each cloud function has its own environment. Read more <a href="https://www.redhat.com/en/topics/containers/what-is-container-orchestration">here</a>.</p><p>Typically, deployment can be availed using the following techniques:</p><ol><li>Ship from the local machine</li><li>Deploy from source control</li><li>Deploy from Cloud Console</li><li>Deploy with the Cloud Functions API</li></ol><p>Google Cloud comes up with something called Functions Framework to run and debug your functions locally for supported runtime. It makes testing and debugging easier.</p><p>Choosing the right strategy: The right strategy can depend on your business, wallet, urgency, design, and a lot of other factors. Generally, deployment from source control is the way to go for many.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/0*0ABJ-q6771lX8Fl6" /></figure><p>This is largely because this strategy provides benefits on VCS, feature-based development, continuous integration, development coherence, and automated deployment. The source code already stored as commits can use tags on each commit and these tags can be used to deploy the code. While most teams prefer to work in coherence, yet prefer independent control over code modules, small-scale projects typically do not define a strategic deployment strategy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/0*jnk-d-5MsA3b0hxU" /></figure><p>These tags act as a trigger to the building engines of cloud providers. Good strategies include a mechanism to only build the difference on code rather than the entire unit. One good example to understand this is a GCP-managed python cloud function built entirely only when there are more modules needed by the environment for that function to work. This can be observed using the time taken to deploy in both cases.</p><p>To be continued! Next on this:</p><ul><li>Managing Cloud Functions</li><li>Cloud Functions and Security</li><li>Deploying Pipeline</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cea55f8d2c8d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to the course]]></title>
            <link>https://medium.com/data-structures-and-algorithms-the-easy-way/introduction-to-the-course-1148fb60f950?source=rss-7eb0d82fcb38------2</link>
            <guid isPermaLink="false">https://medium.com/p/1148fb60f950</guid>
            <dc:creator><![CDATA[Harsh Joshi]]></dc:creator>
            <pubDate>Sat, 28 Nov 2020 18:03:07 GMT</pubDate>
            <atom:updated>2021-07-20T19:34:52.222Z</atom:updated>
            <content:encoded><![CDATA[<h3>DSA: The Easy Way!</h3><p>Hello!<br>Let’s walk through the foundation and basics of this series. This is an introductory story on concepts we will learn.</p><p>A data structure can be defined as the group of data elements that provides an efficient way of storing and organizing data in the computer so that it can be used efficiently.</p><p>Example — Arrays, Linked List, Stack, Queue, etc.</p><p>Each of these data structures has a different special way of organizing data so we choose the data structure based on the requirement.</p><h4>Data Structure Types</h4><p>We have two types of data structures:</p><ol><li>Linear Data Structure</li><li>Non-linear Data Structure</li></ol><p><strong>Linear data structures:</strong> Elements of Linear data structures are accessed in a sequential manner, however, the elements can be stored in these data structures in any order. Examples of the linear data structure are LinkedList, Stack, Queue, and Array.</p><p><strong>Non-linear data structures: </strong>Elements of non-linear data structures are stores and accessed in a non-linear order. Examples of the non-linear data structures are Tree and Graphs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*bhcJl0IWdUvBPa7T.jpg" /></figure><p><a href="https://www.geeksforgeeks.org/introduction-to-data-structures-10-most-commonly-used-data-structures/">More Here</a></p><h3>Algorithms</h3><p>The word Algorithm means “a process or set of rules to be followed in calculations or other problem-solving operations”.</p><p>In order to write an algorithm, the following things are needed as a pre-requisite:</p><p>1 The problem that is to be solved by this algorithm.<br>2 The constraints of the problem that must be considered while solving the problem.<br>3 The input to be taken to solve the problem.<br>4 The output to be expected when the problem is solved.<br>5 The solution to this problem, in the given constraints.</p><h3>Programming Languages</h3><p>A vocabulary and set of grammatical rules (syntax) for instructing a computer to perform specific tasks.<br>• Programming languages can be used to create computer programs.<br>• The term programming language usually refers to high-level languages, such as BASIC, C, C++, COBOL, FORTRAN, Ada, and Pascal.</p><p>You eventually need to convert your program into machine language so that the computer can understand it.<br>There are two ways to do this:<br>1 – Compile the program<br>2 – Interpret the program</p><p><strong>Compile </strong>is to transform a program written in a high-level programming language from source code into object code. This can be done by using a tool called a compiler. A compiler reads the whole source code and translates it into a complete machine code program to perform the required tasks which is output as a new file.</p><p><strong>The interpreter </strong>is a program that executes instructions written in a high-level language. An interpreter reads the source code one instruction or line at a time, converts this line into machine code, and executes it.</p><p>What we might miss in these definitions — <strong>One of them works in real-time.</strong></p><p>There are three types of programming language:<br>– Machine language (Low-level language) — Binary <br>– Assembly language (Low-level language) — Used in Microprocessors.<br>– High-level language</p><h3>Object-Oriented Basics</h3><p><a href="https://medium.com/@cancerian0684/what-are-four-basic-principles-of-object-oriented-programming-645af8b43727">Click me</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1WjjjBRVO1Zc4f84.jpeg" /></figure><h3>OOPS Interview Concepts</h3><ul><li>Class</li><li>Object</li><li>Principles of OOPs</li><li>Constructor(s)</li><li>Overloading/Overriding</li></ul><p>{Rest on OOPs in a separate story}</p><h3>Basics Questions</h3><p>1 — Reverse an array</p><p>2 — Check if the string is Palindrome</p><p>3 — Check if string a is a substring of string b</p><p>4 — Factorial of a number</p><p>5 — Print Fibonacci series /Find nth Fibonacci Number</p><p>6 — Reverse a number</p><p>7 — Print Patterns</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1148fb60f950" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-structures-and-algorithms-the-easy-way/introduction-to-the-course-1148fb60f950">Introduction to the course</a> was originally published in <a href="https://medium.com/data-structures-and-algorithms-the-easy-way">Data Structures and Algorithms — The easy Way</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Education and Learning: Bridging the Gap- A Student’s Perspective!]]></title>
            <link>https://josharsh.medium.com/education-and-learning-bridging-the-gap-a-students-perspective-5571a0b7359f?source=rss-7eb0d82fcb38------2</link>
            <guid isPermaLink="false">https://medium.com/p/5571a0b7359f</guid>
            <category><![CDATA[students]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[education]]></category>
            <dc:creator><![CDATA[Harsh Joshi]]></dc:creator>
            <pubDate>Thu, 16 Apr 2020 12:00:56 GMT</pubDate>
            <atom:updated>2020-04-16T12:00:56.277Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>My name is Harsh and I am a Student.</blockquote><p>The world is changing and with it are changing those aspects of life which govern the very principles of running it. Luxuries have changed and so have the needs and necessities. With every tomorrow, there lies a new possibility of a change. The present standards of education are a concrete reflection of it. While some enjoy being stagnant with the metamorphosis around, some choose to make a move and be a part of the change.</p><p>The revolution in the education system has developed a model that separates education and learning, which for long went hand in hand. As a matter of fact, the dictionary always had separate meanings for these words. “Education”, it says is, “the process of receiving or giving systematic instruction, especially at a school or university” while “Learning” is the “the acquisition of knowledge or skills through study, experience, or being taught”. Interestingly, this model is not a work of design, it rather is a work of vested interest to have an axe to grind. With the duties evenly distributed between the facilitator and the learner, good or not, the fact is independent goals have been set for the two. While the system works around continuously improving itself, or precisely in pursuit of adapting to new pedagogy, evolving curriculum and in utilizing jargons for portrayal, the learner doesn’t get straight into this functioning. The system does not intervene with his job i.e. to learn.</p><p>It certainly is not fair to put the sword of the blame on the education system, which in most of the ways has been meeting the assigned goals, evolving with time and leaving no stones unturned to get better while the counterpart is struggling with a said simpler role. In addition, the learner struggles to match with the pace of its counterpart’s growth. Metaphorically, he is a tadpole put in the most sophisticated and well-developed ICU and given a role of growing ahead of time because many like him are tending to grow ahead of time, though they appear unnatural. He who grows gives him pressure and ultimately if he can’t, he does not want. Here, it also is important to understand that ICU is meant for critical operations while growing is largely fundamental and complementary in nature. Having said that, in no ways whatsoever, ICU is faulty for being what it is, but for what it is not.</p><p>The thin line is education is revolutionizing, while learning is mostly stagnant. It thus gives a notion of the model, which someday emerged, as a result of the change without an individual designing it. It sustained well that no one ever questioned it, rather the blames were always exchanged between the two, the education system and the learner. The system faced blame for business-oriented approach, the involvement of political dimensions and money while the learner was blamed for not being able to cope up to avail the plethora of resources available to him.</p><p>It is not, in my opinion, the result of their individual underperformance but their collective independence from each other. Therefore education today needs learning while learning requires all dimensions of education. Their very dependence of each other bridges the gap between the two.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VEHXIRX-1VTUBUoQxub1fQ.png" /></figure><p>I leave you with a crossword, “ <strong>Educated learner takes it with hesitation at first of events”.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5571a0b7359f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Magic of Bitwise Operators]]></title>
            <link>https://josharsh.medium.com/the-magic-of-bitwise-operators-62fdbbdad995?source=rss-7eb0d82fcb38------2</link>
            <guid isPermaLink="false">https://medium.com/p/62fdbbdad995</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[bitwise-operator]]></category>
            <category><![CDATA[competitive-programming]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Harsh Joshi]]></dc:creator>
            <pubDate>Wed, 26 Feb 2020 04:56:22 GMT</pubDate>
            <atom:updated>2020-02-26T04:56:22.938Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Bitwise Operators are one of my favourite tools in programming. They seem overwhelming at first but once one becomes acquainted, it’s a piece of cake. Bitwise operators are intriguing because of their practical implementation. These work on the mathematics of logic and fundamental operations involving bits (which are used in Machine Instructions).</blockquote><p>Bitwise operators directly deal with the binary of a number. Bitwise operators are interesting to study because they have a logic which is similar to none. This is the reason many don’t quite understand the working at the start. It is very important to know before starting to study Bitwise Operators that these operate on binary and binary is not the same as a decimal. The concept of the binary of a number in itself is a standalone subject to study and brings along different dimensions and has different representation.</p><p><strong>Let’s Talk Bitwise Now</strong></p><p>In programming, there is a concept of “signed” and “unsigned” integers. These representations denote positive and negative numbers. This concept is not generic to all the programming languages but is explicit to some.</p><p>Java, for instance, does not support “unsigned” integers whereas C++ has support for both “signed” and “unsigned” numbers. Signed numbers are represented using 2’s Complement.</p><h4>2’s Complement While Writing Code to a Problem:</h4><p>While it is very easy to take 2’s complement mathematically. It becomes very intriguing when it has to be done programmatically.</p><p>Mathematically, Given a binary number, we flip the bits and add 1 to obtain the 2’s complement of a number. But to do this programmatically, first of all, we won’t be given the binary number, rather the decimal equivalent of it and we will not be asked to find 2’s complement rather use this concept to derive some other result.</p><blockquote>Let us understand with an example:</blockquote><blockquote>The binary representation of 2 is 10.</blockquote><blockquote>To obtain the 2’s complement of 010 we flip the bits to make it 101 and add 1 to make it 110 which is 6 in decimal. So the 2’s complement of 2 is 6 (In 3-bit Representation)</blockquote><p>It is very important to note that, the bit representation i.e. the total number of bits used to represent the number plays a huge role in determining these calculations. In the examples above we calculated the 2’s complement assuming a 3-bit representation i.e. a number can be represented using 3 bits.</p><p>To do it programmatically,</p><p>The 2&#39;s complement of input x in k-bit representation is <strong>2^k-x.</strong></p><p>For example, 2’s complement of 2 is 2³-2= 6 which is 101 in binary.</p><p>TO BE CONTINUED…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62fdbbdad995" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started With C++ STL]]></title>
            <link>https://josharsh.medium.com/getting-started-with-c-stl-fcec28ab702c?source=rss-7eb0d82fcb38------2</link>
            <guid isPermaLink="false">https://medium.com/p/fcec28ab702c</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[vector]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[stl]]></category>
            <category><![CDATA[cps]]></category>
            <dc:creator><![CDATA[Harsh Joshi]]></dc:creator>
            <pubDate>Tue, 18 Feb 2020 12:47:17 GMT</pubDate>
            <atom:updated>2020-02-18T14:04:22.766Z</atom:updated>
            <content:encoded><![CDATA[<p>C++ is a widely used language for developing applications such as games, operating systems, and low-level programming that requires better control of hardware on the PC or server.</p><p>C++ is considered a very efficient language for competitive programming because it is faster in execution than many other programming languages. You may have noticed, though, that many coders manage to write their code much more quickly and concisely than you.</p><h3>Introduction To C++ STL Libraries</h3><p>The Standard Template Library is a collection of C++ template classes which provide common programming data structures and functions. The functions and structures are vectors, lists, stacks, etc.</p><p>STL has four components</p><ol><li>Algorithms</li><li>Containers</li><li>Functions</li><li>Iterators</li></ol><p><strong>Algorithms: </strong>The header algorithm defines a collection of functions specially designed to be used on ranges of elements. They act on containers and provide means for various operations for the contents of the containers.</p><p><strong>Containers: </strong>Containers or container classes store objects and data. There are in total seven standards “first-class” container classes and three container adaptor classes and only seven header files that provide access to these containers or container adaptors.</p><p><strong>Functions: </strong>The STL includes classes that overload the function call operator. Instances of such classes are called function objects or functors. Functors allow the working of the associated function to be customized with the help of parameters to be passed.</p><p><strong>Iterators: </strong>As the name suggests, iterators are used for working upon a sequence of values. They are the major feature that allows generality in STL.</p><h3>Containers in C++ STL:</h3><p><strong>Vectors: </strong>Vectors hold the properties of dynamic arrays and are capable to resize themselves upon insertions and deletions. This makes their use more efficient than using arrays.</p><p>Vectors are traversed using iterators.</p><h4>Example</h4><pre>#include &lt;iostream&gt;<br>#include &lt;vector&gt;<br>using namespace std;<br>int main(){<br>vector&lt;int&gt; cards;<br>for(int i=0;i&lt;5;++i)<br>{<br>cards.push_back(i);<br>}<br>for(int i=0;i&lt;5;++i)<br>{<br>cout&lt;&lt;cards[i];<br>} <br>}</pre><h4>Basics of Vectors:</h4><pre>#include&lt;iostream&gt;<br>using namespace std;<br>#include&lt;vector&gt;<br>#include&lt;algorithm&gt;<br>int main(){<br>vector&lt;int&gt; A= {1,2,5,4,6};<br>//To access the second element</pre><pre>cout&lt;&lt;A[1]&lt;&lt;endl;</pre><pre>//To use functions like sort<br>sort(A.begin(),A.end()); //O(nlogn)</pre><pre>//Binary Search in Vectors<br>bool present= binary_search(A.begin(),A.end(),3); //False</pre><pre>cout&lt;&lt;present&lt;&lt;endl;</pre><pre>//To insert more elements: push_back();</pre><pre>A.push_back(0);</pre><pre>//To iterate a vector an iterator is used. To display the value holded by iterator pointer is used.</pre><pre>vector&lt;int&gt;::iterator itr;</pre><pre>for(itr=A.begin();itr!=A.end();++itr){</pre><pre>cout&lt;&lt;*itr;</pre><pre>}</pre><pre>cout&lt;&lt;endl;</pre><pre>bool present2=binary_search(A.begin(),A.end(),6);//TRUE</pre><pre>cout&lt;&lt;present2&lt;&lt;endl;</pre><pre>//lowerbound means that first element greater than the given element which includes the given element</pre><pre>//Upper bound finds the first strictly greater element than the given element</pre><pre>vector&lt;int&gt;::iterator i1=lower_bound(A.begin(),A.end(),2);</pre><pre>cout&lt;&lt; *i1&lt;&lt;endl;</pre><pre>vector&lt;int&gt;::iterator i2=upper_bound(A.begin(),A.end(),2);</pre><pre>cout&lt;&lt;*i2&lt;&lt;endl;</pre><pre>//lower bound and upper bound on a sorted vector is done in O(logn) time.</pre><pre>//To know the number of time a number has occurred, perform upper and lower bound and substract the iterators.</pre><pre>cout&lt;&lt;i2-i1&lt;&lt;endl; //Prints 1</pre><pre>}</pre><pre>#include&lt;iostream&gt;</pre><pre>#include&lt;vector&gt;</pre><pre>#include&lt;algorithm&gt;</pre><pre>using namespace std;</pre><pre>bool f(int a,int b){</pre><pre>return a&gt;b;</pre><pre>cout&lt;&lt;x&lt;&lt;” “&lt;&lt;endl;</pre><pre>}</pre><pre>}</pre><pre>}</pre><pre>int main(){</pre><pre>vector&lt;int&gt; A={77,88,55,11,33,33};</pre><pre>vector&lt;int&gt;::iterator itr;</pre><pre>for(itr=A.begin();itr!=A.end();++itr){</pre><pre>cout&lt;&lt;*itr&lt;&lt;” “;</pre><pre>}</pre><pre>cout&lt;&lt;endl;</pre><pre>sort(A.begin(),A.end());</pre><pre>vector&lt;int&gt;::iterator Aa=lower_bound(A.begin(),A.end(),33);</pre><pre>vector&lt;int&gt;::iterator B=upper_bound(A.begin(),A.end(),33);</pre><pre>cout&lt;&lt;*Aa&lt;&lt;endl&lt;&lt;*B;</pre><pre>//To know how many times a number occurs in a vector simply do lower_bound followed by the upper_bound and the difference of the two is the number of times the number has occurred.</pre><pre>cout&lt;&lt; endl&lt;&lt;B-Aa&lt;&lt;” “&lt;&lt;endl;</pre><pre>//To sort a vector in decreasing order, there is a overloaded function sort() which takes in a comparator function</pre><pre>// f() as the third argument. The comparator function returns true or false and to sort in descending order the value</pre><pre>// it returns should be return a&lt;b;The comparator function is always declared in the global space.</pre><pre>sort(A.begin(),A.end(),f);</pre><pre>vector&lt;int&gt;::iterator it1;</pre><pre>for(it1=A.begin();it1!=A.end();++it1){</pre><pre>cout&lt;&lt; *it1&lt;&lt;” “;</pre><pre>}<br>//To print Elements of a vector instead of vectors, simply for loops can be given</pre><pre>for(int x: A){</pre><pre>cout&lt;&lt;x&lt;&lt; “ ”&lt;&lt;endl; <br>}<br>}</pre><h4>Auto keyword in C++:</h4><p>(Type Inference in C++)</p><p>Type inference means automatic deduction of the data type of an expression. The type deduction after c++ 11 can be left on the compiler itself and the type can be assigned at the runtime.</p><p><strong>auto keyword:</strong></p><p>It specifies the type of variable that is being declared from its initializer. If the return type of a function is auto then it will be evaluated by the return type expression at the runtime.</p><pre>#include &lt;iostream&gt;<br>#include &lt;vector&gt;<br>#include &lt;algorithm&gt;<br>using namespace std;<br>int main(){<br>vector&lt;int&gt; A={1,4,2,6,8,3};<br>for(auto it=A.begin();it!=A.end();++it){<br>cout&lt;&lt; *it&lt;&lt; “ “;}}</pre><p>The code given above prints 1 4 2 6 8 3</p><pre>#include &lt;iostream&gt;<br>#include &lt;vector&gt;<br>#include &lt;algorithm&gt;<br>using namespace std;<br>int main(){<br>vector&lt;int&gt; A={1,4,2,6,8,3};<br>for(auto it=A.begin();it!=A.end();++it){<br>cout&lt;&lt; *it&lt;&lt; “ “;}</pre><pre>//To iterate over values of a vector and change them</pre><pre>// use the refernce</pre><pre>for(int &amp;x:A){<br>x++;<br>cout&lt;&lt;x&lt;&lt;” “;}<br>}</pre><h3>List in C++ STL</h3><p>Normally list in STL refers to doubly linked list. In doubly linked list insertion, deletion and traversal of elements can be done from both of the endpoints. Like vectors, lists are also sequential containers. Lists allow non-contiguous memory allocation.</p><p>Note: To implement a singly linked list, the forward list is used.</p><p><strong>Example:</strong></p><p><strong>1 — List: Basic Example</strong></p><pre>#<strong>include</strong> &lt;iostream&gt;<br>#<strong>include</strong>&lt;list&gt;<br>#<strong>include</strong>&lt;iterator&gt;<br><strong>using</strong> <strong>namespace</strong> std;<br><strong>void</strong> <strong>showList</strong>(list&lt;<strong>int</strong>&gt;l){<br> <strong>for</strong>(<strong>auto</strong> it=l.begin();it!=l.end();++it){<br> cout&lt;&lt;” “&lt;&lt;*it&lt;&lt;” “&lt;&lt;endl;<br> }<br>}<br><strong>int</strong> <strong>main</strong>()<br>{<br> list&lt;<strong>int</strong>&gt; l;<br> <strong>for</strong>(<strong>int</strong> i=0;i&lt;10;++i)<br> {<br> l.push_back(i*2);<br> }<br> showList(l);<br>}</pre><p><strong>2 — List insertion at the beginning.</strong></p><pre>#<strong>include</strong> &lt;iostream&gt;<br>#<strong>include</strong>&lt;list&gt;<br>#<strong>include</strong>&lt;iterator&gt;<br><strong>using</strong> <strong>namespace</strong> std;<br><strong>void</strong> <strong>showList</strong>(list&lt;<strong>int</strong>&gt;l)<br>{<br><strong>for</strong>(<strong>auto</strong> it=l.begin();it!=l.end();++it)<br>{<br> cout&lt;&lt;” “&lt;&lt;*it&lt;&lt;” “&lt;&lt;endl;<br>}<br>}<br><strong>int</strong> <strong>main</strong>()<br>{<br> list&lt;<strong>int</strong>&gt; l;<br> <strong>for</strong>(<strong>int</strong> i=0;i&lt;10;++i)<br> {<br> l.push_fron(i*3);<br> }<br> showList(l);<br>}</pre><p><strong>Operations to be used along List:</strong></p><ul><li>push_back(g) — Adds a new element at the back</li><li>push_front(g) — Adds new element at the front</li><li>pop_back() — Deletes the element from the back</li><li>pop_front() — Deletes the element from the start</li><li>reverse() — Reverses the linked list</li><li>sort() — sorts the list in ascending order</li><li>front() — Returns the value of the first element</li><li>back() — Returns the value of the last element</li><li>list:: begin() — Returns an iterator pointing to the first element</li><li>list:: end() — Returns the iterator pointing to the last element</li><li>rbegin() — returns a reverse iterator</li><li>rend() — returns a reverse iterator which points to the position before the beginning of the list</li><li>empty() — Checks if the list is empty or not</li><li>insert() — Inserts new elements at the specified position</li><li>erase() — Removes a single element from the list at a specified position</li><li>assign() — Assigns new elements to list by replacing current elements and resizes the list</li><li>remove() — Removes all elements from the list (Which are equal to the given element)</li><li>size() — Returns the size of the list</li><li>list:: clear() — Removes all elements and makes the size of list 0</li><li>list:: swap() — Swap elements of the contents of one list with another list of same type and size.</li><li>list splice() — Used to transfer elements from one list to another</li><li>merge() — Merges two sorted lists into one</li><li>emplace() — Extends list by inserting a new element at a given position</li></ul><h3>Set in C++ STL:</h3><p>Set is an associate container. A set is used to hold unique elements. (The value of an element is used to identify the element). The set does not allows modification of values of elements once they have been stored in a set.</p><p><strong>Example:</strong></p><pre>#<strong>include</strong>&lt;iostream&gt;<br>#<strong>include</strong>&lt;set&gt;<br>#<strong>include</strong>&lt;iterator&gt;<br><strong>using</strong> <strong>namespace</strong> std;<br><strong>int</strong> <strong>main</strong>(){<br>set&lt;<strong>int</strong>&gt; s;<br>s.insert(1);<br>s.insert(2);<br>s.insert(3);<br>s.insert(4);<br><strong>auto</strong> it;<br><strong>for</strong>(it=s.begin();it!=s.end();++it){<br>cout&lt;&lt; “ “&lt;&lt;*it&lt;&lt;endl;<br>}<br>}</pre><p>//Output: 1 2 3 4</p><p><strong>Program : Using Stack to store elements in strictly descending order:</strong></p><pre>#<strong>include</strong>&lt;iostream&gt;<br>#incude&lt;set&gt;<br>#<strong>include</strong>&lt;iterator&gt;<br><strong>using</strong> <strong>namespace</strong> std;<br><strong>int</strong> <strong>main</strong>(){<br>set&lt;<strong>int</strong>,greater&lt;<strong>int</strong>&gt;&gt; s;<br>s.insert(5);<br>s.insert(1);<br>s.insert(3);<br><strong>for</strong>(<strong>auto</strong> it=s.begin();it!=s.end();++it){<br>cout&lt;&lt; “ “&lt;&lt;*it&lt;&lt;endll<br>}<br>//OUTPUT: 5 3 1</pre><p><strong>Operations in STL:</strong></p><ul><li>begin() — Returns an iterator to the first element in the set</li><li>end() — Returns an iterator to the theoretical element that follows last element in the set</li><li>size() — Returns the size of the set</li><li>max_size() — Returns the maximum number of elements that a set can hold</li><li>empty() — Returns whether the set is empty.</li><li>cbegin() — Returns a constant iterator pointing to the last element in the container</li><li>crend() — Returns a constant iterator pointing to the position just before the first element in the container</li><li>insert(const g) — Inserts a new element in the set</li><li>erase(iterator position) — Removes elements from the specified position</li><li>erase(const g) — Removes element “g” from the set</li><li>clear() — Removes all elements from the set</li><li>find(const g) — Returns an iterator the element (if found, else returns the iterator to the end)</li><li>count(const g) — Returns 1 or 0 based on element ‘g’ is present in the set or not.</li></ul><pre>Press ENTER to exit console.</pre><h3>Map in C++</h3><p>Maps are associative containers that store the elements in key-value pairs. The value is mapped with a key.</p><p>Maps are a part of the C++ STL. Maps are associative containers that store elements formed by a combination of a key-value and a mapped value, following a specific order.</p><h3>Map Template:</h3><pre>std::map &lt;key_type, data_type&gt;</pre><h3>Declaration:</h3><pre>map&lt;string,int&gt;m; //Creates a map m where key_type is of type string and data_type is of type int.</pre><h3>Size:</h3><pre>int length=m.size(); //Gives the size of the map.</pre><h3>Insert:</h3><pre>m.insert(make_pair(“hello”,9)); //Here the pair is inserted into the map where the key is “hello” and the value associated with it is 9.</pre><h3>Erasing an element:</h3><pre>m.erase(val); //Erases the pair from the map where the key_type is val.</pre><h3>Finding an element:</h3><pre>map&lt;string,int&gt;::iterator itr=m.find(val); //Gives the iterator to the element val if it is found otherwise returns m.end() .</pre><p>E.g.</p><pre>map&lt;string,<strong>int</strong>&gt;::iterator itr=m.find(“Maps”); //If Maps is not present as the key value then itr==m.end().</pre><h3>Accessing the value stored in the key:</h3><p>To get the value stored of the key “MAPS” we can do m[“MAPS”] or we can get the iterator using the find function and then by itr-&gt;second we can access the value</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fcec28ab702c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Structures and Algorithms— Complete Reference]]></title>
            <link>https://josharsh.medium.com/data-structures-and-algorithms-complete-reference-e0d52b12fb71?source=rss-7eb0d82fcb38------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0d52b12fb71</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[linked-lists]]></category>
            <category><![CDATA[stack]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[Harsh Joshi]]></dc:creator>
            <pubDate>Thu, 06 Feb 2020 08:52:49 GMT</pubDate>
            <atom:updated>2020-02-06T08:52:49.855Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>This is a complete reference material on data structures. I have tried to put in all the material from my learning experience of data structures. The material begins from scratch and goes on to talk about advanced topics. For ease, it has been sectioned into chapters.</blockquote><blockquote>To Contribute to the material go to <a href="https://github.com/josharsh/MyDSHandbook">https://github.com/josharsh/MyDSHandbook</a> and open a Pull Request</blockquote><h3>CHAPTER 1: AN INTRODUCTION</h3><p>One of the most fundamental concepts in programming and computer science is the concept of data structures. Data structures refer to the way of organizing data for efficient usage. The data stored on your hard drive, the data on the RAM, data on pen drives, CD ROMs and all other places you can think of, the key underlying concept is of data structures that powers these devices to work efficiently.</p><p><em>NOTE: Data structures not just describe the storage of data piled into a memory unit, rather describe the data management alongside storing the data.</em></p><h4>HOTS: It is easier to search a word from a dictionary because the words in the dictionary have been organized for that purpose. This is one of the many uses of data structures.</h4><h3>WHY SO MANY OF DATA STRUCTURES FOR A SIMPLE PURPOSE?:</h3><p>Different kind of data exists and a different set of organization techniques and tools are adhered to while storing data and hence there required is a need for different types of data structures.</p><p>e.g. A key-value pair data cannot be simply stored in a simple static array.</p><p>Other factors which govern the choice of data structures is memory management, system utilization, usage, etc.</p><h3>HOLD ON!! IT’S PERHAPS NOT WHAT YOU THOUGHT:</h3><p>It was earlier mentioned that the data stored on devices like hard drives and pen drives is powered with the data structures. This statement has high chances of getting misinterpreted because data structures are not physical structures rather logical ones.</p><p><em>“A physical data structure refers to the actual organization of data on a storage device. The logical data structure refers to how the information appears to a program or user. For example, a data file is a collection of information stored together. This is its logical structure”</em></p><p><strong>DEFINITION: </strong>A data structure is a format for data organization, management, and storage which enables efficient access and updating.</p><h3>WAYS TO LOOK AT A DATA STRUCTURE:</h3><p>Whatever is being talked about in this section does not specify the types of data structures rather it talks about the two perspectives data structures should be looked at with.</p><ol><li>LOGICAL VIEW</li><li>IMPLEMENTATIONAL VIEW</li></ol><p>Two eyes, Two perspectives! It’s one for each. Let’s dive into details:</p><p>The logical view of data structures defines the associated operations that would be carried out.</p><p><em>So, this perspective of data structure does not do anything, it only defines stuff and hence is never used in the actual implementation but it is handy because it is the backbone of the actual implementation</em>.</p><p>Wohaa! That was a long sentence to understand in one go.</p><p>In simpler words, logical view describes <strong>WHAT</strong> but not <strong>HOW. </strong>It is because of this reason that these data structures are called<strong> Abstract Data Types.</strong></p><p><em>“Abstract Data type (ADT) is a type (or class) for objects whose behaviour is defined by a set of value and a set of operations.” — GeeksForGeeks</em></p><p>Let’s break it down with an example:</p><p>There is something called a Car. The attributes of a car (only to name a few) are:</p><ul><li>It has four wheels.</li><li>It provides roof</li><li>It drives us to place we want to go</li></ul><p>Okay! Now, do we actually in practice own something called the car in our daily lives. We actually own an extension of the car. We might own a Maruti Swift Desire or even a Honda Amaze. These are cars too but these are the ones actually used (Implementational View).</p><p>The attributes are (Honda Amaze):</p><ul><li>Mileage: 23.8 kmpl</li><li>Engine Displ. : 1498 cc</li><li>Transmission: Automatic</li><li>Fuel Type: Diesel</li><li>Boot Space: 420</li></ul><p>If you are familiar with the concepts of <strong>Aggregation and Association </strong>and<strong> is-a relationship</strong> you might be finding it easy. Otherwise, think of it as there are some generic data structures which only define the operations which the structure will carry out without talking about how will it do it. And then come the implemented data structures (concrete data structures) which extend the Abstract data types (generic data structures) to describe how will the operations actually implemented.</p><p>One of the example in terms of programming is:</p><p>A list is an abstract data type which defines that there is some capacity for the elements to be stored in sequential order here and array extends it to define explicit properties and operations describing the extended properties.</p><h3>CHAPTER 2: LIST AS AN ABSTRACT DATA TYPE</h3><p>In general, a collection of objects which are of the same type form a list. A list can be a group of words, a group of car names or anything that follows the above-mentioned definition.</p><p>Now that we are aware of what an abstract data type is, Let define list as an abstract data type.</p><p>An abstract data type will only define the data to be stored and the associated operations for handling the data.</p><p>In view of a list which contains a similar group of objects so the abstract view of it can be summarized as:</p><ul><li>It contains a fixed number of elements of the same datatype</li><li>It allows accessing the element present at any location.</li><li>Write/Modify any element at any position</li></ul><p>The abstract view is not limited to only these points. However, if we think of the concrete implementation for such an abstract data type, a familiar name that strikes is an <strong>Array.</strong></p><h3>Array:</h3><p>An array stores the items in contiguous memory locations. It can be seen as a concrete implementation of the abstract data type list. The contiguously allocated memory makes it easy to access the elements using the base address and indices.</p><p>Based on the implementation, arrays can be categorized as static or dynamic. Static arrays have fixed memory already assigned at the time of definition. Dynamic arrays are capable to change the size as per the run time requirements.</p><p><em>Note: In case of the dynamic array, whenever the maximum size of the array is reached, a new array with a larger size is created and the content of the previous array is copied to that array. (Because it is not possible to extend the size of the already created array)</em></p><p><em>The memory for the previous array is made free. Since the operation to copy content from one array to another is costly in terms of time, every time the array is full, a new array of double the capacity of previous is created.</em></p><p>Every element in an array is uniquely identified by the index.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/0*Qq9T8SrkumonYFXh" /></figure><h3>Array Programs:</h3><p><strong>PROGRAM 1: </strong>Write a function rotate(ar[], d, n) that rotates arr[] of size n by d elements.</p><pre><strong>#include &lt;iostream&gt;</strong><br><strong>using</strong> <strong>namespace</strong> std;<br><strong>void</strong> <strong>leftRotateByOne</strong>(<strong>int</strong> arr[],<strong>int</strong> n);<br><strong>void</strong> <strong>leftRotate</strong>(<strong>int</strong> arr[],<strong>int</strong> k,<strong>int</strong> n);<br><strong>void</strong><br><strong>leftRotate</strong> (<strong>int</strong> arr[], <strong>int</strong> k, <strong>int</strong> n)<br>{<br> <strong>for</strong> (<strong>int</strong> i = 0; i &lt; k; ++i)<br> {<br> leftRotateByOne (arr, n);<br> }<br>}</pre><pre><strong>void</strong><br><strong>leftRotateByOne</strong> (<strong>int</strong> arr[], <strong>int</strong> n)<br>{<br> <strong>int</strong> temp = arr[0];<br> <strong>int</strong> i;<br> <strong>for</strong> (i = 0; i &lt; n — 1; ++i)<br> {<br> arr[i] = arr[i + 1];</pre><pre>}<br> arr[i] = temp;<br>}</pre><pre><strong>int</strong><br><strong>main</strong> ()<br>{<br> <strong>int</strong> arr[] = { 1, 2, 3, 4, 5, 6, 7 };<br> <strong>int</strong> n = <strong>sizeof</strong> (arr) / <strong>sizeof</strong> (arr[0]);<br> leftRotate (arr, 2, n);<br> <strong>for</strong> (<strong>int</strong> i = 0; i &lt; n; ++i)<br> {<br> cout &lt;&lt; arr[i];<br> <br> }<br>}</pre><p><strong>Program:</strong> Array Reversal</p><pre><strong>#include &lt;iostream&gt;</strong><br><strong>using</strong> <strong>namespace</strong> std;</pre><pre><strong>int</strong> <strong>main</strong>(){<br> <strong>int</strong> arr[]={ 1,2,3,4,5,6 }; <em>//Input Array which has to be reversed.</em><br> <strong>int</strong> start=0;<br> <strong>int</strong> end=<strong>sizeof</strong>(arr)/<strong>sizeof</strong>(arr[0])-1;<br> <strong>while</strong>(start&lt;end){<br> <strong>int</strong> temp=arr[start];<br> arr[start]=arr[end];<br> arr[end]=temp;<br> <br> start++;<br> end — ;<br> }<br> <strong>for</strong>(<strong>int</strong> i=0;i&lt;<strong>sizeof</strong>(arr)/<strong>sizeof</strong>(arr[0]);++i){<br> cout&lt;&lt;arr[i];<br> <br>}}</pre><p><strong>Program:</strong> Array Rearrangement such that if found element i should be at an ith position.</p><pre><strong>#include &lt;stdio.h&gt;</strong><br><strong>using</strong> <strong>namespace</strong> std;</pre><pre><strong>int</strong> <strong>main</strong>(){<br> <strong>int</strong> arr[]={ 1,2,3,4,5,6 }; <em>//Input Array which has to be reversed.</em><br> <strong>int</strong> n=<strong>sizeof</strong>(arr)/<strong>sizeof</strong>(arr[0]);<br> <strong>for</strong>(<strong>int</strong> i=0;i&lt;n;++i){<br> <strong>if</strong>(arr[i]&gt;=0 &amp;&amp; arr[i] !=i){<br> arr[arr[i]]=(arr[arr[i]]+arr[i])-(arr[i]=arr[arr[i]]);<br> }<br> <strong>else</strong>{<br> i++;<br> }<br> }<br> <strong>for</strong>(<strong>int</strong> i=0;i&lt;n;++i){<br> cout&lt;&lt;arr[i];<br> }<br>}</pre><h3>Limitations of Array:</h3><p>Let us assume a fixed section of computer memory.</p><p>Suppose each segment in the memory is of 1 byte.</p><p>Now,</p><p>If a programmer types <strong>int x;</strong> in the program, the equivalent memory (4 Bytes) is allocated in the memory. Similar Happens with the array.</p><p>When an array is declared</p><p><strong>int arr[5];</strong></p><p>This means that 5 integer type elements are to be stored in the array. So, the space that would be required in memory would be 5 * 4 = 20 Bytes. Now, when it comes to memory allocation, <strong>arrays require contiguous memory. </strong>This requires that 20 bytes of memory (20 segments) should be continuously free in memory area else the array can’t be allocated memory.</p><p>This is one of the biggest limitations of the array.</p><p><strong>CONTIGUOUS MEMORY ALLOCATION AND ARRAY:</strong></p><p>The answer to why array requires contiguous memory is, array uses a base addressing for indexing the elements. Since the base address is increment sequentially to retrieve subsequent elements, the addresses in memory need to be contiguous too.</p><p><strong>NOTE:</strong></p><p><strong><em>Dynamic Array Memory Allocation:</em></strong></p><p><em>As it was mentioned earlier that dynamic array is capable to adjust its size, but the memory management somehow does not support the extension of array size if there is no contiguous memory available. To solve this a new array with the double size is created wherever the contiguous memory is found. If not found, the dynamic array can’t be created.</em></p><h3>INTRODUCTION TO LINKED LIST</h3><p>Starting off from the problem of memory management in case of arrays, it can be a solution that memory is sought for one individual element of the list, rather than the list (array) as a whole.</p><p>In the linked list, the request to memory is made of one element at a time.</p><p>Again, if the previous example is considered. When 4 elements of integer types are to be stored, then instead of asking memory for the entire collection to be stored at one place, memory can be asked for separate units of data each linked to each other via some means. This means the need for contiguous memory has been overcome.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/0*Sq1of1iYejrtVq0c.PNG" /></figure><p>Suppose there are two elements to be stored {4,5}. For each element, a new request for memory allocation is taken and memory is allocated for each element ( Not the entire list as a whole). It is also not required that the elements 4 and 5 be stored contiguously in the memory area.</p><p>But somehow these two elements need to be linked to each other so that the list can be accessed continuously. For this purpose, pointers are used.</p><p>Technically, each entry in a linked list is called a node. A node is much more than the raw data to be inserted. A node contains the data and the link to traverse to the previous and next node.</p><p>So the node can be represented using the structure as:</p><pre>struct <strong>node</strong> <strong>{<br>int</strong> data;<br><strong>node* next</strong>;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/0*vBIwKS0_Qbv7t8Ux.PNG" /></figure><p>In the above-mentioned code example, the second component of the structure is marked as <strong>node*</strong> which marks that the second field of the node will only store an address.</p><p>In the linked list, the first node is also called the<strong> head</strong> node. The address field of the last node of the linked list points to null, which marks the end of the list.</p><p>The only information we need to have is the address of the head node. Once we have the address of the head node, we can traverse the entire list. Although it is advantageous in terms of memory, the drawback of using a linked list is that no element of the list is directly accessible which means for accessing the 4th element, one would need to first access 1st, 2nd, and 3rd elements compulsorily.</p><p>The time taken to access elements has O(n) complexity. (because each element has to be traversed and in the worst case the element to be searched will be the last element of this list.</p><h3>CHAPTER 3: ARRAY &amp; LINKED LIST ANALYSIS</h3><p>Before starting this chapter, it should be clear that it is not suited to say one data structure is better than other. The usage of every data structure comes along different applications of it.</p><p>E.g if there’s a requirement to quickly access elements and memory is sufficient, an array can be used but if memory has to managed efficiently and access time is not given priority, Linked List is a good option to use.</p><p>The differences between the data structures can be measured as functions or in terms of <strong>cost</strong>, <strong>speed</strong>, etc. Some of these parameters are:</p><h3>Accessing Elements :</h3><p><strong>Array:</strong> Since an array is a contiguous block of memory, it takes constant time to access elements in the array. It as also mentioned earlier that the array utilizes base addressing to access the elements.</p><p>Time Complexity: O(1)</p><p><strong>Linked List: </strong>There are independent nodes stored in discontinuous memory locations. Initially, the address of the head node is given and to access the elements in a list we need to traverse sequentially. So it takes linear time.</p><p>Time Complexity: O(n)</p><h3>Memory Usage :</h3><p><strong>Array:</strong> To declare an array we need to know the memory needed before inserting values in it because contiguous memory is required for the array. To achieve the flexibility of insertion, we initially assign a large block of memory to the array is utilize only some part for initially storing the values. So there is a heavy chance of memory wastage in the array.</p><p><strong>Linked List: </strong>Since the linked list does not need to be contiguously allocated and each node is inserted in memory at the time it is created, there is no memory wastage involved in the linked list. Although in a linked list, extra memory is used for pointer variables.</p><p>NOTE: Memory usage differs from memory management. When it comes to usage, a linked list also uses the amount of memory which is used by array because of pointer overhead.</p><p>Here’s an example:</p><p>But this case would differ and the linked list would be useful is the data part is very large and the pointer is small.</p><h3>Cost Of Insertion:</h3><p><strong>At the Beginning:</strong></p><p><strong>ARRAY</strong>: O(n)</p><p><strong>LINKED LIST</strong>: O(1)</p><p><strong>At the end:</strong></p><p><strong>Array:</strong> O(1) if the array is not full and O(n) if the array is full</p><p><strong>Linked List: </strong>O(n)</p><p><strong>At ith Position:</strong></p><p><strong>Array:</strong> O(n)</p><p><strong>Linked List: </strong>O(n)</p><h3>Chapter 4: Concept Of Pointers in C/C++</h3><p>Pointers are the variable which holds the address of other variables. Pointers are used to carry references to other variables. Pointer Variables are strongly typed. A pointer variable of a particular data type is needed to store the address of the corresponding variable. For an integer type variable, the pointer has to be an integer, this extends to the fact that a char value can only be pointed by a character pointer and also goes similar for other data types.</p><p>When we talk about memory management in programming, we generally deal with the Random Access Memory. Whenever a variable is declared, a certain amount of memory in the RAM is allocated which is based on the data type of the variable being used in the program. This allocation in memory in allocated while the program is in running and the addresses allocated to the variables might be different every time a program runs. A pointer variable is represented using an Asterisk.</p><p><strong>EXAMPLE</strong>:</p><p>A working example of pointers in c++ :</p><pre><strong>int</strong> a;<br>a=5;<br>int *p;<br>p=&amp;a;<br>cout &lt;&lt; a &lt;&lt; endl;<br>cout &lt;&lt; p &lt;&lt; endl;<br>cout &lt;&lt; *p &lt;&lt; endl;</pre><p>Let us assume a fixed section of computer memory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/0*Ksis6IcaVIWyDP-2.PNG" /></figure><p>Suppose each segment in the memory is of 1 byte.</p><p>Now,</p><p>If a programmer types <strong>int x;</strong> in the program, the equivalent memory (4 Bytes) is allocated in the memory. When a <strong>pointer *p</strong> for x is created, the pointer points to <strong>integer x</strong> and<strong> *p</strong> stores the value of <strong>a</strong> whereas<strong> p</strong> stores the address of <strong>a</strong>.</p><h3>WHY DIFFERENT DATA TYPES FOR DIFFERENT POINTERS?</h3><p>It might strike that why do pointers have to be strongly typed when they only need to store addresses. The answer is pointers do a lot more than simply storing the addresses. Pointers are also used to dereference the addresses so that we can access and modify the values in these addresses.</p><h3>HOW ARE NUMBERS ACTUALLY STORED?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/0*Adv_1INxQgQ3mfcr.PNG" /></figure><p>This is the binary representation of 1010</p><p>In modern-day compilers, an integer takes 4 bytes. The memory is byte-addressable.</p><p>The leftmost bit stores the information whether the integer is positive or negative. This bit is also called the <strong>sign bit.</strong></p><p><strong>int</strong> a = 1010;<br><strong>int</strong> *p=&amp;a;</p><p>if the value of <strong>p</strong> is printed, <strong>202</strong> is printed because the address of <strong>byte 0</strong> is used to address the integer variable. Now, if we print *p, the machine understands that p is an integer pointer hence it has 4 bytes beginning with address 202. This is because different pointer data types are needed.</p><p><strong>NOTE: The way the information is stored for float, char and different data types is different in memory.</strong></p><pre><strong>#include &lt;stdio.h&gt;</strong></pre><pre><strong>int</strong> <strong>main</strong>()<br>{<br> <strong>int</strong> a=1010;<br> <strong>int</strong> *p;<br> p=&amp;a;<br> printf(“Value of p is %d and value of *p is %d”,p,*p);<br> <strong>char</strong> *c;<br> c=(<strong>char</strong>*)p;<br> printf(“Value of c is %d and value of *c is %d”,c,*c);<br>}</pre><pre><em>/*OUTPUT:<br>Value of p is -629538260 and value of *p is 1010 Value of c is -629<br>538260 and value of *c is -14 <br> <br>…Program finished with exit code 0 <br>Press ENTER to exit console. */</em></pre><p>This happens because char is allocated one byte in memory, once the char pointer points to the typecasted integer it only takes the leftmost byte i.e. Least Significant Byte (LSB) and since it is char so does not extend to check memory for 4 next bytes and outputs decimal equivalent of LSB of binary 1010.</p><h3>Void Pointer:</h3><p>A void pointer is a generic pointer type which does not correspond to any particular data type and thus is called void. A void pointer can not be dereferenced i.e. * can not be used with a void pointer</p><p>e.g:</p><pre><strong>int</strong> a=1010;<br><strong>void</strong> *v;<br>v= &amp;a;<br><strong>int</strong> *p;<br>p=&amp;a;<br>v=p <em>//Correct </em><br>printf(“%d”, v*); <em>//Incorrect Because Void Pointer can not be dereferenced.</em></pre><h3>Pointer to Pointer Concept:</h3><p>It was made clear in the previous text that pointers are strongly typed. A pointer can point to a memory location which contains the corresponding data type.</p><p><strong>int a;</strong></p><p><strong>int *p;</strong></p><p><strong>p=&amp;a;</strong></p><p>But there’s an interesting fact that a pointer can point to another pointer variable. It is represented using double asterisk **.</p><p><strong>int a;</strong></p><p><strong>int *p;</strong></p><p><strong>p=&amp;a;</strong></p><p><strong>int **q;</strong></p><p><strong>q=&amp;p;</strong></p><h3>USE CASES:</h3><h3>As Function Arguments (Call By Reference):</h3><p>Memory is reserved for a program in execution and it is split as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/197/0*zyhUHMqrUyB4a2o-.PNG" /></figure><p>These portions in memory describe the type of data they hold during the execution of the program. Out of these Stack, Static/Global and Code(Text) are fixed whereas Heap is resizable during the execution of the program.</p><p>Codes stores all the instructions. This includes declarations and statements. The static and global variables are dealing with a specific memory assigned. The local variables and methods are stored in the Stack.</p><p>Suppose there’s a program,</p><pre><strong>#include &lt;stdio.h&gt;</strong><br><strong>void</strong> <strong>increment</strong>(<strong>int</strong> a)</pre><pre>{<br>a=a+1;</pre><pre>}<br><strong>int</strong> <strong>main</strong>()</pre><pre>{<br><strong>int</strong> a;<br>a=10;<br>increment(a);<br>printf(“%d”,a);</pre><pre>}</pre><p>The program intends to increase the value of a variable named a but it outputs 10 and does not show the incremented value.</p><p>This is because:</p><p>When the program is in execution, at first main method is triggered so all the information associated with the main function is stored in the <strong>stack</strong>. This information typically includes a local variable, returning to which function, etc. So, some part of stack memory is occupied with information about the main function, which is called a <strong>stack frame</strong>. Each function has a stack frame in the stack.</p><p>When the main function calls increment function, the execution of the main function is stopped for some time and the control is passed to the called function. Now, another stack frame is created for increment function. In this stack frame, local variables related to increment function are created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/0*VcS4ohQjfuX2rJu4.PNG" /></figure><p>The real problem was when the<strong> a=a+1</strong> statement is called, the local variable pertaining to the stack frame of function increment gets incremented which only got the value of <strong>a</strong> from the main function as the argument. The value of<strong> a</strong> was copied to a local variable of increment function and the same got incremented and thus did not result in incrementing the local variable of the main function because the local variables are not accessible outside the <strong>stack frame</strong>.</p><p>Once the control is passed back to the main function, the stack frame created for increment function is cleared. This implies that <strong>the lifetime of a local variable is till the time the function is executing</strong>.</p><p>The above-described scenario is called Call By Value.</p><p>If we look from a different perspective called Call By Reference, The code would look like,</p><pre><strong>#include &lt;stdio.h&gt;</strong><br><strong>int</strong> <strong>increment</strong>( <strong>int</strong> *p)<br>{ *p= (*p)+1;<br>}<br><strong>int</strong> <strong>main</strong>()<br>{<br><strong>int</strong> a;<br>a=10;<br>increment(&amp;a);<br>printf(“%d”, a); <em>//Prints 11</em><br>}</pre><p>While executing the value which is stored in the local variable p ( for function increment) is the address of memory location where a ( of function main) is stored, Hence the value of a is incremented using call By reference.</p><h3>Concept of Array and Pointers:</h3><p>When talking about an array, the concept of pointers is very crucial.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/0*dwr6J_vY4ka-OW3q.PNG" /></figure><p>Suppose the array named A is allocated memory as shown above. Since one integer takes 4 bytes the address of next integer will be 4 bytes more than the previous address.</p><p>int a= { 2 , 4 , 6 , 8 , 10 }</p><p>To print the address of initial element we can print &amp;a[0] or we can also print the name of the array. To print the initial value<strong> *a</strong> can be used and for every subsequent value <strong>*(a + 1)</strong></p><pre><strong>#include &lt;stdio.h&gt;</strong><br><strong>int</strong> <strong>main</strong>()<br>{<br> <strong>int</strong> a[]= {2,4,6,8,10};<br> printf(“Array is: { 2 , 4 , 6 , 8 , 10 } \n”); <br> printf(“First Address Using printing &amp;a[0]: %d \n”,&amp;a[0]);<br> printf(“First Address Using printing a :%d \n”,a);<br> printf(“Value at First Address Using *&amp;a[0] is : %d \n”,*&amp;a[0]);<br> printf(“Value at First Address Using *a is : %d \n”,*a);<br> printf(“Value at First Address Using *(a+1) is : %d \n”,*(a+1));<br>}</pre><h3>Array as Function Arguments</h3><p>Pointer have a role to play when array is passed as function argument.</p><p>e.g. To print the sum of an array, the code can be like</p><pre><strong>#include &lt;stdio.h&gt;</strong><br><strong>int</strong> <strong>calculateSum</strong>(<strong>int</strong> a[], <strong>int</strong> n){<br> <strong>int</strong> i,sum;<br> <strong>for</strong>(i=0;i&lt;n;++i){<br> sum+=a[i];<br> }<br> <strong>return</strong> sum;<br>}<br><strong>int</strong> <strong>main</strong>()<br>{<br> <strong>int</strong> a[]= {2,4,6,8,10};<br> <strong>int</strong> n=<strong>sizeof</strong>(a)/<strong>sizeof</strong>(a[0]);<br> <strong>int</strong> sum=calculateSum(a,n);<br> printf(“%d”,sum);<br>}</pre><p>This code calls calculateSum function from main and passes the array and size of array to it. It calculates the sum and outputs 30.</p><p>But if we wanted to calculate the size of array in the function calculateSum(), the code would look like,</p><pre><strong>#include &lt;stdio.h&gt;</strong><br><strong>int</strong> <strong>calculateSum</strong>(<strong>int</strong> a[]){<br> <strong>int</strong> i,sum;<br> <strong>int</strong> n=<strong>sizeof</strong>(a)/<strong>sizeof</strong>(a[0]);<br> printf(“%d \n”,n);<br> <strong>for</strong>(i=0;i&lt;n;++i){<br> sum+=a[i];<br> }<br> <strong>return</strong> sum;<br>}<br><strong>int</strong> <strong>main</strong>()<br>{<br> <strong>int</strong> a[]= {2,4,6,8,10};<br> <strong>int</strong> sum=calculateSum(a);<br> printf(“%d”,sum);<br>}</pre><p>But this outputs the incorrect sum</p><p>This is because whenever the array is passed as a function argument, the compiler understands it as a pointer to the first element of the array. This is done to save memory because arrays can be really large and to create a local array and copy content would require a large amount of memory in many cases. So the local memory created for the function calculated points to the array in the main function using a pointer.</p><h3>Pointers and Dynamic Memory</h3><p>Memory assigned to a program is divided into 4 segments as mentioned earlier.</p><p>There 4 segments of memory are used to store various components of a program. The memory assigned for the stack, static/global and code segments can’t be changed during run time. When we talk about the stack, it is used for the local storage while the program is running.</p><p>When a function is called, a stack frame is allocated for the function and the required memory is assigned. The most recent called function sits on top of the stack and after the function is done processing, the stack frame is cleared.</p><p><em>The memory for the stack is assigned by the operating system but the actual allocation of memory for each function (the local variables etc. for the function) happens during the runtime.</em></p><p>If the number of functions is too many or by any other reason the memory assigned to the stack if totally utilized, it is called <strong>Stack Overflow.</strong></p><p>One of the common examples of stack overflow is when the recursion goes infinitely.</p><p>The allocation and deallocation of memory in the stack happen by a set rule, When a function is called it is pushed on the top of the stack and when it finishes execution it is popped out from the stack. The scope of the variable does not change when the function is in the stack.</p><p><strong>Example for Demonstration:</strong></p><pre><strong>#include &lt;stdio.h&gt;</strong><br><strong>int</strong> total;<br><strong>int</strong> <strong>Square</strong>(<strong>int</strong> x)<br>{<br><strong>return</strong> x*x;<br>}<br><strong>int</strong> <strong>SquareOfSum</strong>(<strong>int</strong> x , <strong>int</strong> y)<br>{<br><strong>int</strong> z = Square(x+y);<br><strong>return</strong> z;<br>}<br><strong>int</strong> <strong>main</strong>()<br>{<br><strong>int</strong> a= 4, b= 8;<br>total=SquareOfSum(a,b);<br>printf(“Output = %d” , total);<br>}</pre><p>Most Recently Called Function Sits on Top of the stack and is also the one to be popped first.</p><p><strong>PHASE 1:</strong> main() is called and the program begins.</p><p><strong>PHASE 2:</strong> main() calls SumOfSquares()</p><p><strong>PHASE 3: </strong>SumOfSquares() calls Square()</p><p><strong>PHASE 4:</strong> Square returns value and memory for Square() is deallocated</p><p><strong>PHASE 5: </strong>Control is passed back to the main function</p><p><strong>PHASE 6: </strong>Program finishes, main() is popped of stack and stack memory is empty</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/0*PJ1viHOmPARem45N.PNG" /></figure><h3>Heap:</h3><p>Unlike the stack and other segments, the memory for the heap is not fixed. Its size can change during the run time. Also, there is no set rule for memory allocation and deallocation ( like push and pop in the stack).</p><p>A programmer can decide the amount of memory to be used and the duration for which the memory has to be used. A heap can grow as long as the system does not run out of memory.</p><p><strong><em>Note:</em></strong><em> When talking about a memory associated with heap or stack, it is always referred to the Random Access Memory.</em></p><p>Heap is also called a free pool of memory. The actual implementation of the heap is complex and varies from system to system, but the abstract view of the heap can be seen as a free pool of memory.</p><p>Heap is also called dynamic memory. Using heap is also called dynamic memory allocation.</p><p><strong><em>NOTE: </em></strong><em>The term “Heap” is also used to denote a data structure but when talking about memory, it does not refer to the “Heap” as used in data structures. Although the data structure “Stack” is the same in memory as in data structures. The implementation of the stack, the data structure is used in memory but in terms of the heap in memory, it only refers to a free pool of memory.</em></p><h3>Dynamic Memory Allocation In C:</h3><p>Dynamic Memory allocation in C is carried out using 4 functions</p><ol><li>malloc</li><li>calloc</li><li>realloc</li><li>free</li></ol><p>Dynamic Memory Allocation in C++ is carried out using 2 operators</p><ol><li>new</li><li>delete</li></ol><p><strong><em>Note: </em></strong><em>Since C++ has backward compatibility, the functions of C can also be used in C++.</em></p><p><strong>C Program for Dynamic Memory Allocation:</strong></p><pre><strong>#include &lt;stdio.h&gt;</strong><br><strong>#include &lt;stdlib.h&gt;</strong><br><strong>int</strong> <strong>main</strong>()<br>{<br><strong>int</strong> a; <em>//Since it is a local variable, it goes to stack</em><br><strong>int</strong> *p;<br>p = (<strong>int</strong>*) malloc (<strong>sizeof</strong>(<strong>int</strong>));<br><em>/* Malloc returns a void pointer to the starting address of the memory block assigned. We have to typecast because it returns void pointer */</em> <br>*p=10;<br><em>// free(p);</em><br>p= (<strong>int</strong>*) malloc(<strong>sizeof</strong>(<strong>int</strong>));<br>*p=20;<br><em>/* a new memory block to store 20 is assigned at some other address in heap and the previous is not cleared */</em><br>free(p);<br>p=(<strong>int</strong>*) malloc (20*<strong>sizeof</strong>(<strong>int</strong>));</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/0*D3C53NUwFKucJzsj.PNG" /></figure><p><strong>IMPORTANT POINTS:</strong></p><ul><li>Memory in heap is not cleared when the pointer is changed, it needs to be cleared every time when the value/variable stored is not required</li><li>The malloc(size) function returns a void pointer to the address of the memory in a heap so the void pointer has to be converted to integer pointer for storing integer values.</li><li>To allocate memory for array in heap, the malloc function needs to be given the size of the array.</li><li>For integer: 4 * Number of Elements</li><li>For Character Array: 1 * Number of Elements</li><li>Assigning/Changing values in heap is only done using referencing i.e. obtaining a pointer to the address of heap and then assigning the value using an asterisk. ( *p =10 )</li></ul><h3>Dynamic Memory Allocation in C++</h3><p>In C++ the two operators used are New and Delete. They are used similar to malloc and free functions in C. The difference is they are typesafe which means that the typecasting in not required.</p><p><strong>Syntax:</strong></p><pre><strong>int</strong> *p;<br>p = <strong>new</strong> <strong>int</strong>;<br>*p = 10;<br>p= <strong>new</strong> <strong>int</strong>[20];<br><strong>delete</strong>[] p;</pre><h3>Malloc, Calloc, Realloc and Free in C</h3><h3>Malloc:</h3><p>Malloc is the most frequently used function for dynamic memory allocation.</p><p><strong>Definition: </strong>void* malloc( size_t size)</p><ul><li>It returns a void pointer which has to be typecasted</li><li>size_t means the only positive number can be entered (unsigned)</li><li>Assignment can only be done using dereferencing (Using pointers)</li></ul><p><strong>Syntax: </strong>int *p=(int*) malloc(sizeof(int));</p><h3>Calloc:</h3><p>calloc is similar to malloc but takes in two parameters. The first argument is the number of elements of particular data type and the second argument is the size of the data type.</p><p><strong>Syntax:</strong></p><p>int *p = (int*) calloc(1,sizeof(int));</p><p>Another difference between malloc and calloc is that <strong>malloc</strong> initializes the assigned memory location with some garbage values while <strong>calloc</strong> does not initialize the values.</p><h3>Calloc:</h3><p>If we already have a dynamic block of memory and we need to change the size of the memory, then realloc is used.</p><p><strong>Syntax:</strong></p><p>int *p = (int*) realloc(void *ptr, size_t size);</p><p>*ptr= Address of initial block.</p><h3>EXAMPLES:</h3><pre><strong>#include &lt;stdio.h&gt;</strong></pre><pre><strong>int</strong> <strong>main</strong>()<br>{<br> <strong>int</strong> n;<br> scanf(“%d”,&amp;n);<br> <strong>int</strong> *arr=(<strong>int</strong>*) malloc(n*<strong>sizeof</strong>(<strong>int</strong>));<br> arr[0]=1;<br> printf(“%d”,arr[0]);<br>}</pre><pre><strong>#include &lt;stdio.h&gt;</strong></pre><pre><strong>int</strong> <strong>main</strong>()<br>{<br> <strong>int</strong> *p;<br> p=(<strong>int</strong>*)malloc(<strong>sizeof</strong>(<strong>int</strong>));<br> *p=10;<br> printf(“%d”,*p);<br>}</pre><h3>Function Pointers:</h3><p>Function Pointers are used to store the address of functions. It simpler words they are used to point to the function and the function can be called by dereferencing it. The compiler converts the high-level language code to the machine-understandable binary code. The execution of a program does not directly happen from the secondary storage (Where the program is stored). The executable instructions are copied to the Code/Text section of the Random Access Memory and then the execution begins.</p><p>Normally, the execution of a program is sequential. But it can be non-sequential when the instruction asks to go to another instruction at some different address i.e. during the function calls.</p><p>So function pointers contain the initial address of the memory location of all the instruction of a function. A function pointer is created using the return type of the function.</p><p><strong>Syntax:</strong></p><pre><strong>#include &lt;stdio.h&gt;</strong><br><strong>int</strong> <strong>Add</strong>(<strong>int</strong> a, <strong>int</strong> b)<br>{<br><strong>return</strong> a+b;<br>}<br><strong>int</strong> <strong>main</strong>(){<br><strong>int</strong> c;<br><strong>int</strong> (*p)(<strong>int</strong>,<strong>int</strong>);<br>p=&amp;Add;<br>c=(*p)(2,3);<br>}</pre><h3>CHAPTER 5: IMPLEMENTATION OF LINKED LIST</h3><ul><li>The only identifier for a linked list is the address of the first block of the linked list</li><li>Implementation Declaration in C:</li></ul><pre>struct Node</pre><pre>{</pre><pre>int data;</pre><pre>struct Node* link;</pre><pre>}</pre><ul><li>Implementation Declaration in C++:</li></ul><p>struct Node</p><p>{</p><p>int data;</p><p>Node* link;</p><p>}</p><h3>Chapter 6: Asymptotic Analysis</h3><h3>Time Complexity of a Program:</h3><p>A program to find the total number of prime numbers between a given range can be solved by two approaches. One is to iterate from <strong>1 to</strong> to<strong> n-1</strong> and check the satisfying numbers to be prime while the other is to iterate till <strong>square root of n</strong>, onto the same conditions.</p><p>When we talk about the time complexity of a program, we generally deal with large input sizes, because the factor of time does not simply imply smaller input values. In the above-given condition to find a number of prime numbers till a number n.</p><p>Let n= 10000;</p><p>Suppose each iteration takes 1 ms to complete.</p><p><strong>Case 1: </strong>Iterating till <strong>n-1</strong>:</p><p>Total number of iterations = 99999</p><p>Total Time Taken = 99999*10^-3= 99.999= 1 minute 40 Seconds</p><p><strong>Case2: </strong>Iterating till<strong> sqrt(n):</strong></p><p>Total number of iterations: 315 (approx)</p><p>Total Time Taken= 315 ms = 0.315 seconds</p><p>The performance of both cases regarding the time taken to execute it very evident with the previous example. This is why Time Complexity plays a crucial role in programming solutions for problems requiring large inputs.</p><h3>Basics Of Asymptotic Notations:</h3><p>The time complexity of an algorithm can be determined and expressed mathematically using Asymptotic Notations. When we talk about Time complexity, we always refer to the associated algorithm and not the computer program. The complexity of an algorithm can be measured in space and in time. There are three ways to measure it namely best case, average case and the worst case.</p><p>There are different types of asymptotic notations widely used to mathematically represent time complexity. One of the most common ones is the <strong>big-O </strong>notation. The big-O notation generally deals with large inputs. It gives complexity in terms of<strong> input size, N. </strong>The big-O notation is used to test the worst-case complexity. big-O is expressed as <strong>O(complexity term).</strong></p><p><strong>Big-O Basics:</strong></p><ul><li>Constants are ignored i.e. O(5n) is same is O(n)</li><li>Order of complexity is:</li><li><strong>O(1) &lt; O(log n) &lt; O(n) &lt; O (nlogn) &lt; O(n²) &lt; O(2^n) &lt; O(n!)</strong></li></ul><p><strong>Side Note: </strong><a href="https://www.bigocheatsheet.com/"><strong>https://www.bigocheatsheet.com/</strong></a><strong> </strong>is a great tool to learn more about big-O</p><p>Suppose to solve a problem, two algorithms have been devised. Let the running time of algorithm A is a function <strong>f(n)</strong> and the running time of other algorithm is <strong>g(n).</strong> If <strong>g(n) </strong>grows faster than<strong> f(n)</strong> then there must be some values of <strong>n</strong> for which <strong>g(n)</strong> is larger than <strong>f(n).</strong></p><p><strong>Explanation: </strong>There is a function f(n) and another function g(n). The faster growth of functions means that for different values of the independent variable n, the function return larger values. The larger the return values, faster is the growth!</p><p>Now, if g(n) grows faster than f(n) simply means that there must be one independent value of n, let’s say <strong>n* </strong>for which and for values larger than<strong> n* </strong>the value returned by<strong> g(n) </strong>will always be greater than <strong>f(n).</strong></p><h3>i.e g(n*)&gt;=f(n*)</h3><p>This can also be written as<strong> f(n*)&lt;= C.g(n)</strong> where C is a constant.</p><h3>Now, we can say that f(n) is contained in O(g(n)).</h3><h3>Introduction To Asymptotic Analysis:</h3><p>Each algorithm is compared on this basis of time taken to execute and memory required.</p><p><strong>Big-O: </strong>Describes the worst-case running time of an algorithm</p><p><strong>Big Omega (Ω):</strong> Describes the best-case running time of an algorithm</p><p><strong>Big-Theta (θ): </strong>Describes the average running case of an algorithm</p><h3>Analysis of Algorithms:</h3><p>When we talk about design and analysis of an algorithm, the analysis of an algorithm deals with the efficiency of an algorithm. Efficiency is generally measured in terms of time and space complexity. Generally, more than space, time complexity is considered a driving factor for measuring the efficiency of an algorithm. This is because time is a limiting parameter. However, space is comparatively more flexible as memory can be added and removed. In technical words, time depends on the processing speed while space is a function of available memory. Instead of measuring the time complexity in terms of concrete time because in different systems the running time of an algorithm can vary as per the variable specs of the machine it is being executed upon. This is why the abstract units of measurements are utilized to measure the time complexity of the algorithm. This ensures that the time complexity of an algorithm is uniform across systems and machines.</p><p>The abstract units of measurements are based on the steps taken to successfully execute an algorithm. The step is a kind of basic operation. However, the notion of a step varies as per the programming language used. For example, the steps used in assembly language might include fetching the data from registers to the main memory but when devising algorithms to problems, we use a higher-level approach and a programming language like c, c++ or java.</p><p>Basically we measure time complexity in terms of input size. So, if the input is of size n, then the time taken will be a function of n.</p><p><strong>Example:</strong> We have an array of n elements, and we want to sort the array in ascending order. Now any naive algorithm will compare each pair of elements of the array and take time proportional to O(n2) time. [The sequential speed of CPU is about 108 operations per second]</p><h3>Chapter 7: Understanding Algorithms for Sorting</h3><p>When we have a large collection of any sort of data, at times we might need to arrange the data in a particular order. Sorting algorithms if implied over a collection like an array, list etc. sort the constituents of the collection in a particular order. Typically, the order is increasing, decreasing or even alphabetical.</p><p>There are many sorting algorithms associated with every type of collection. Some of the widely known ones are:</p><ul><li>Quick Sort</li><li>Bubble Sort</li><li>Merge Sort</li><li>Insertion Sort</li><li>Selection Sort</li><li>Heap Sort</li><li>Radix Sort</li><li>Bucket Sort</li></ul><p>Time complexities for the algorithms can be given as:</p><p><strong>Algorithm</strong> <strong>Best</strong> <strong>Average</strong> <strong>Worst</strong></p><ul><li>Quick Sort Ω(n log(n)) Θ(n log(n)) O(n²)</li><li>Bubble Sort Ω(n) Θ(n²) O(n²)</li><li>Merge Sort Ω(n log(n)) Θ(n log(n)) O(n log(n))</li><li>Insertion Sort Ω(n) Θ(n²) O(n²)</li><li>Selection Sort Ω(n²) Θ(n²) O(n²)</li><li>Heap Sort Ω(n log(n)) Θ(n log(n)) O(n log(n))</li><li>Radix Sort Ω(nk) Θ(nk) O(nk)</li><li>Bucket Sort Ω(n+k) Θ(n+k) O(n²)</li></ul><h3>Classification of Sorting Algorithms:</h3><p>Sorting algorithms can be classified on the basis of time complexity or space complexity. Time complexity is a measure of the rate of time taken with respect to the input size while space complexity deals with the space taken in memory. With space complexity, there is associated a concept of in-place or constant memory. Some algorithms take constant space while some take memory as the algorithms proceeds in execution ( Local Variables etc.)</p><p>Another important factor is stability. Stability describes the property which preserves of the relative order of elements. e.g. if there is a collection of 4 playing cards and 9 Black Diamond preceded 9 Red Heart, then upon sorting it must be preserved.</p><h3>Understanding Discrete Mathematics for Programming</h3><p>Good knowledge of discrete mathematics helps tackle many programming questions easily.</p><h3>Factorization:</h3><p>A factor of a number N is a number d such that d completely divides N i.e. N%d=0;</p><h3>Character Array and Pointers</h3><p>In C, Strings are represented using character arrays.</p><p><strong>How are the strings stored?</strong></p><p>Size of character array should be = length of string +1</p><p>The extra space of 1 is required to indicate that the string is over. A null character is put on the end of the string. So the rule in C is, the strings are null-terminated.</p><pre>#include&lt;stdio.h&gt;</pre><pre>#include&lt;string.h&gt;</pre><pre>int main()</pre><pre>{</pre><pre>char C[20];</pre><pre>c[0]= ‘H’;</pre><pre>c[1]= ‘A’;</pre><pre>c[2]= ‘R’;</pre><pre>c[3]= ‘S’;</pre><pre>c[4]= ‘H’;</pre><pre>printf(“%s”,C); //Prints something else after “HARSH” because string is not null terminated.</pre><pre>c[5]= ‘\0’;</pre><pre>printf(“%s”,C); //Correctly Prints</pre><pre>int len=strlen(C); //It also counts till null character i.e. len=5</pre><pre>}</pre><p>But while giving string literal the null termination is implicit. i.e. c[20]= “Harsh”, does not require explicit null termination because it is implicitly done.</p><blockquote>This blog is subject to update as I further learning. Keep an eye to keep yourself updated</blockquote><blockquote>REFERENCES: MyCodeschool, GeeksForGeeks, Algorithms (Coursera), Codechef Certification Practice Material</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0d52b12fb71" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Developing Recommender Systems]]></title>
            <link>https://josharsh.medium.com/developing-recommender-systems-bedff2f345da?source=rss-7eb0d82fcb38------2</link>
            <guid isPermaLink="false">https://medium.com/p/bedff2f345da</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[recommender-systems]]></category>
            <category><![CDATA[information]]></category>
            <dc:creator><![CDATA[Harsh Joshi]]></dc:creator>
            <pubDate>Sun, 02 Feb 2020 14:26:02 GMT</pubDate>
            <atom:updated>2020-02-18T12:26:41.743Z</atom:updated>
            <content:encoded><![CDATA[<p>This lesson talks about recommenders systems and goes on to describe developing one.</p><h4>How will the lesson be like?</h4><p>The lesson will be divided into several parts, progressing from basic to intermediate level of learning. <br>I will be writing whatever I have learned during my experience of instinct with Recommender Systems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/0*pWNZeDGGJYTDT895" /><figcaption>Source: Pinterest</figcaption></figure><h4>Introduction To Recommender Systems</h4><p>The topic of recommender systems falls somewhere in the domain of information systems /information retrieval. Basically a Recommender system is a subclass of the information filtering system.</p><blockquote>A recommender system is a model that utilizes the information about a user or product to recommend the item to the user or vice versa.</blockquote><p>The term Recommendation Engine is synonymously used with Recommender Systems.</p><p>Suppose a grocery store uses Recommendation System. If Harsh like deserts then a good recommendation engine would suggest ice cream to him rather than grape juice.</p><p>Practically just Recommendation Engine is not enough, there needs to be a data pipeline that collects whatever input data the model needs. For instance, for a video recommender system inputs can be the last five videos one watched.</p><h4><strong>AMAZING FACT:</strong></h4><blockquote>Recommendation systems are not just about suggesting products to users but at times they can also suggest users for particular products. This is known as targeting. An example of this is finding 1000 most relevant customers for a product that is going to be launched.</blockquote><p>Recommendation systems are not just about products, it can be google suggesting an alternate path to avoid traffic or Linkedin suggesting the possible replies.</p><p>In a nutshell, Recommendation systems can be used by anyone but provide a personalized experience to each user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/0*joaEHm-dRDJ6VchT" /><figcaption>Source: Reddit</figcaption></figure><h4>Types of Recommender Systems:</h4><p><strong>Content-Based:</strong><br>A content-based model uses attributes of the user to recommend new items to the user. <br>This type of model does not include other similar users behaviour while recommending items. The domain is thus very close to an individual user. It is his attributes that help a model decide what to recommend next. A fine example of this is while using an online movie platform, the recommender engine notices a person watching Avengers series movies and thus recommends the DC movies to watch next. Content-based recommendation systems need fine knowledge about user and an apt choice of attributes of items to efficiently work. In the previous example, the movies had to be labelled in various genres, types etc.</p><p><strong>Collaborating Filtering based:</strong><br>The collaborative filtering model is based on an interaction matrix which is deduced on the users and items as rows (or) and columns respectively. In simpler words, the similarity between users and the items is simultaneously used to decide the next recommendation. A fine example is, Person A is recommended a movie X based on the fact that person B who was similar to person A liked that movie. This approach is very popularly used at many sites which provide recommendations like Netflix etc. This approach does not rely on previously constructed features.</p><p><strong>Knowledge-Based</strong><br>The knowledge-based recommendation systems require explicit information about user’s preferences, items or recommendation criteria. These are used when there is enough knowledge to suffice the recommendations.</p><blockquote>A hybrid model is usually the most efficient model to be used as a recommender system<br>In addition to these, deep learning models can also be used to recommend items.</blockquote><p>Example of this can be, to recommend a video to a user the deep learning approach would involve taking user’s behaviour input (Sequence of previously watched videos) and these attributes can be combined in a dense layer of a neural network, and further to a fully connected layer to produce a single value. The objective function can be set to compare the difference of users rating</p><h4>Keynotes:</h4><ul><li>Content filtering uses relevant metadata about a product and uses it to recommend other products. For example, Person A watched 5 movies and liked 3 of them which were sci-fi. Now the recommendation system might suggest another of the same genre. This involved knowing about the item to recommend.</li><li>In collaborative filtering, you don’t need any metadata. Instead, you learn about item similarity and user similarity.</li></ul><p>An example of this can be storing the data in a matrix which indicates whether the user played the complete game, or commented on it or gave it good reviews (Liking towards Game). Since there are many users, and one can not play all games, so this matrix is largely sparse in nature. The main idea behind collaborative filtering is that this very large, item to user matrix can be approximated by <strong>a product of two smaller matrices called the user factors and item factors. Then to find whether the user like the game, we can take the row corresponding to the user and the column corresponding to the game and multiply them to get the predicted rating.</strong></p><ul><li>The best thing about collaborative filtering is that you need not know any metadata about the items. Also, market segmentation is not required.</li><li>If you have metadata, use content filtering. If you have an interactions matrix, then you can use collaborative filtering.</li><li>A better approach is to use a mix of two using neural networks. This model is called the hybrid model and connects all three models.</li></ul><h4>Disadvantages of Recommendation Systems:</h4><ul><li><strong>Item interaction matrix is sparse in nature </strong>(Because out of many many items, there are only a few interactions. There can be billions of users and millions of items and thus most of the entries in the matrix are zero. The problem with sparse matrices is that it gets slow to perform calculations on sparse matrices. (Even if most of the calculations are adding or multiplying by zero)</li><li><strong>Interaction matric is skew in nature</strong>. Some properties are very popular and maybe some users like everything.</li><li><strong>The cold start problem</strong> can occur when there is less information (Usually at the start). For example when a new user is added to the system. For some time the user has no interactions with which to make new recommendations. Also, when the new product is added, the collaborative filtering model might initially show poor results, again due to less interaction with the product.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/0*VvKnlRm2-c2VHYtu" /><figcaption>Source: techboomers.com</figcaption></figure><p>There are <strong>two kinds of user feedbacks </strong>for recommendations systems. One is the direct ratings. An example of this is people giving thumbs up or down on a youtube video.</p><blockquote>The problem with direct rating is that there can be cases when out of 1 million views only 1000 votes have been generated for a video.</blockquote><p>So, another feedback form called the implicit feedback is used. Implicit feedback for the previous example would work on the number of clicks, a number of times played and other such implicit features to provide feedback about the video. This is the indirect method to collect feedback. Also, implicit feedback solves the problem of availability of explicit feedback. (Even though explicit feedback is ground truth)</p><p>At the time of inference, in absence of explicit rating/feedback. If there is sufficient data, the model can include implicit feedback to learn an explicit rating. The input layer takes explicit ratings, and explicit ratings are used as labels. The model is trained to infer an explicit rating that can be further fed to the recommended engine.</p><h3>Building a Simple Vector-Based Model:</h3><p>Content-Based Recommendation Systems :</p><p>Content-based filtering works on local user choices. For example, the previous like data can be used to recommend new items to the user. Item features which are similar to previously liked items are recommended. This can be based on liking or based on explicit feedback.</p><p>This is independent of other users interaction</p><p><strong>Embedding space</strong> is the <strong>space</strong> in which the data is <strong>embedded</strong> after dimensionality reduction. Its dimensionality is typically lower than that of the ambient <strong>space</strong></p><p>Content-based recommender systems measure the similarity of a pair of elements in an embedding space.</p><h3>Similarity Measures:</h3><p>An embedding is a map from our collection of items to some finite-dimensional vector space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*dk4yjXkeHUmAveJPZj8PGQ.png" /></figure><p>A similarity measure is just a metric that exactly defines how similar the items are to each other. (In the same embedding space).</p><p>There are many similarity measures. One of the most commonly used is the Dot Product.</p><p>Other measures include cosine similarity, among many others.</p><h3>Building a User Vector</h3><p>Let there be a set of movies to recommend a user from. More the granularity of the movie features, genres etc. is, the precise the information will be. Let there be 5 movie genres.</p><p>Given their previous movie ratings, we can describe our user in terms of the same features we use to describe our movies. To do this we can scale the movie description matrix by a factor of user’s feedback. Then the resulting vector is normalized. The resulting vector is called the user feature vector. This is to give an approximation of where the idea sits in the embedding space of features based on the previous ratings of various movie feature matrix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*wvweRPNoyEACM2mKNnpUbA.png" /><figcaption>Building A User Vector</figcaption></figure><p>Here A, B, C, D and E are the movie features which have been initially marked to denote if the user liked that movie. Further with the rating value, they have been scaled up and normalized to denote the user in the same embedding space.</p><h3>Making Recommendations:</h3><p>Multiply User-feature vector with movie vector and the add the movies component-wise and the score obtained the dot product similar score of the recommendation. Please note that there can be another similarity measure other than dot product.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*CBk1tJlFM9JQC6_3LbOFFA.png" /><figcaption>Making Recommendations</figcaption></figure><h3>Making Recommendations for Many Users</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*6yh1nDwqHztjZHwEN0fgBg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*wlO2ZhFwbGhNe0i49Boq5A.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bedff2f345da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Recommender Systems]]></title>
            <link>https://medium.com/series/recommender-systems-ba680b2def6a?source=rss-7eb0d82fcb38------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba680b2def6a</guid>
            <dc:creator><![CDATA[Harsh Joshi]]></dc:creator>
            <pubDate>Sun, 02 Feb 2020 14:20:47 GMT</pubDate>
            <atom:updated>2020-02-02T14:21:28.862Z</atom:updated>
            <content:encoded><![CDATA[<h3>Recommender Systems</h3><p>Lesson 1- An Introduction</p><blockquote><strong>A series of lessons on Recommender Systems- By Josharsh</strong></blockquote><p>Recommender Systems are widely popular today. Be it Amazon showing you products to buy or Netflix showing you the next movie suggestion. It is all somewhere using the concepts of Recommendation Systems.</p><p>I am writing this series of lessons as a part of my learning experience of recommender systems.</p><h4>How will the series be like?</h4><p>The series will be divided into several lessons, progressing from basic to intermediate level of learning. <br>I will be writing whatever I have learned during my experience of instinct with Recommender Systems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/0*pWNZeDGGJYTDT895" /><figcaption>Source: Pinterest</figcaption></figure><h4>Introduction To Recommender Systems</h4><p>The topic of recommender systems falls somewhere in the domain of information systems /information retrieval. Basically a Recommender system is a subclass of the information filtering system.</p><blockquote>A recommender system is a model that utilizes the information about a user or product to recommend the item to the user or vice versa.</blockquote><p>The term Recommendation Engine is synonymously used with Recommender Systems.</p><p>Suppose a grocery store uses Recommendation System. If Harsh like deserts then a good recommendation engine would suggest ice cream to him rather than grape juice.</p><p>Practically just Recommendation Engine is not enough, there needs to be a data pipeline that collects whatever input data the model needs. For instance, for a video recommender system inputs can be the last five videos one watched.</p><blockquote>AMAZING FACT:</blockquote><blockquote>Recommendation systems are not just about suggesting products to users but at times they can also suggest users for particular products. This is known as targeting. An example of this is finding 1000 most relevant customers for a product that is going to be launched.</blockquote><p>Recommendation systems are not just about products, it can be google suggesting an alternate path to avoid traffic or Linkedin suggesting the possible replies.</p><p>In a nutshell, Recommendation systems can be used by anyone but provide a personalized experience to each user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/0*joaEHm-dRDJ6VchT" /><figcaption>Source: Reddit</figcaption></figure><h3>Recommender Systems</h3><p>Lesson 2- Types</p><h4>Types of Recommender Systems:</h4><p><strong>Content-Based:</strong><br>A content-based model uses attributes of the user to recommend new items to the user. <br>This type of model does not include other similar users behaviour while recommending items. The domain is thus very close to an individual user. It is his attributes that help a model decide what to recommend next. A fine example of this is while using an online movie platform, the recommender engine notices a person watching Avengers series movies and thus recommends the DC movies to watch next. Content-based recommendation systems need fine knowledge about user and an apt choice of attributes of items to efficiently work. In the previous example, the movies had to be labelled in various genres, types etc.</p><p><strong>Collaborating Filtering based:</strong><br>The collaborative filtering model is based on an interaction matrix which is deduced on the users and items as rows (or) and columns respectively. In simpler words, the similarity between users and the items is simultaneously used to decide the next recommendation. A fine example is, Person A is recommended a movie X based on the fact that person B who was similar to person A liked that movie. This approach is very popularly used at many sites which provide recommendations like Netflix etc. This approach does not rely on previously constructed features.</p><p><strong>Knowledge-Based</strong><br>The knowledge-based recommendation systems require explicit information about user’s preferences, items or recommendation criteria. These are used when there is enough knowledge to suffice the recommendations.</p><blockquote>A hybrid model is usually the most efficient model to be used as a recommender system<br>In addition to these, deep learning models can also be used to recommend items.</blockquote><p>Example of this can be, to recommend a video to a user the deep learning approach would involve taking user’s behaviour input (Sequence of previously watched videos) and these attributes can be combined in a dense layer of a neural network, and further to a fully connected layer to produce a single value. The objective function can be set to compare the difference of users rating</p><h4>Keynotes:</h4><ul><li>Content filtering uses relevant metadata about a product and uses it to recommend other products. For example, Person A watched 5 movies and liked 3 of them which were sci-fi. Now the recommendation system might suggest another of the same genre. This involved knowing about the item to recommend.</li><li>In collaborative filtering, you don’t need any metadata. Instead, you learn about item similarity and user similarity.</li></ul><p>An example of this can be storing the data in a matrix which indicates whether the user played the complete game, or commented on it or gave it good reviews (Liking towards Game). Since there are many users, and one can not play all games, so this matrix is largely sparse in nature. The main idea behind collaborative filtering is that this very large, item to user matrix can be approximated by <strong>a product of two smaller matrices called the user factors and item factors. Then to find whether the user like the game, we can take the row corresponding to the user and the column corresponding to the game and multiply them to get the predicted rating.</strong></p><ul><li>The best thing about collaborative filtering is that you need not know any metadata about the items. Also, market segmentation is not required.</li><li>If you have metadata, use content filtering. If you have an interactions matrix, then you can use collaborative filtering.</li><li>A better approach is to use a mix of two using neural networks. This model is called the hybrid model and connects all three models.</li></ul><h3>Recommender Systems</h3><p>Lesson 2- Disadvantages</p><h4>Disadvantages of Recommendation Systems:</h4><ul><li><strong>Item interaction matrix is sparse in nature </strong>(Because out of many many items, there are only a few interactions. There can be billions of users and millions of items and thus most of the entries in the matrix are zero. The problem with sparse matrices is that it gets slow to perform calculations on sparse matrices. (Even if most of the calculations are adding or multiplying by zero)</li><li><strong>Interaction matric is skew in nature</strong>. Some properties are very popular and maybe some users like everything.</li><li><strong>The cold start problem</strong> can occur when there is less information (Usually at the start). For example when a new user is added to the system. For some time the user has no interactions with which to make new recommendations. Also, when the new product is added, the collaborative filtering model might initially show poor results, again due to less interaction with the product.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/0*VvKnlRm2-c2VHYtu" /><figcaption>Source: techboomers.com</figcaption></figure><p>There are <strong>two kinds of user feedbacks </strong>for recommendations systems. One is the direct ratings. An example of this is people giving thumbs up or down on a youtube video.</p><blockquote>The problem with direct rating is that there can be cases when out of 1 million views only 1000 votes have been generated for a video.</blockquote><p>So, another feedback form called the implicit feedback is used. Implicit feedback for the previous example would work on the number of clicks, a number of times played and other such implicit features to provide feedback about the video. This is the indirect method to collect feedback. Also, implicit feedback solves the problem of availability of explicit feedback. (Even though explicit feedback is ground truth)</p><p>At the time of inference, in absence of explicit rating/feedback. If there is sufficient data, the model can include implicit feedback to learn an explicit rating. The input layer takes explicit ratings, and explicit ratings are used as labels. The model is trained to infer an explicit rating that can be further fed to the recommended engine.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba680b2def6a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DS Handbook: Concept of Pointers]]></title>
            <link>https://josharsh.medium.com/ds-handbook-concept-of-pointers-fd58d79974e0?source=rss-7eb0d82fcb38------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd58d79974e0</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[pointers]]></category>
            <dc:creator><![CDATA[Harsh Joshi]]></dc:creator>
            <pubDate>Mon, 04 Nov 2019 16:45:07 GMT</pubDate>
            <atom:updated>2019-11-04T16:45:07.082Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>For a complete tutorial on Data structures visit: https://github.com/josharsh/MyDSHandbook</blockquote><h3>Pointers in C/C++</h3><p>Pointers are the variable that holds the address of other variables. Pointers are used to carry references to other variables. Pointer Variables are strongly typed. A pointer variable of a particular data type is needed to store the address of the corresponding variable. For an integer type variable, the pointer has to be an integer, this extends to the fact that a char value can only be pointed by a character pointer and also goes similar for other data types.</p><p>When we talk about memory management in programming, we generally deal with the Random Access Memory. Whenever a variable is declared, a certain amount of memory in the RAM is allocated which is based on the data type of the variable being used in the program. This allocation in memory in allocated while the program is in running and the addresses allocated to the variables might be different every time a program runs. A pointer variable is represented using an Asterisk.</p><p>EXAMPLE:</p><p>A working example of pointers in c++ :</p><pre>int a;<br>a=5;<br>Int *p;<br>p=&amp;a;<br>cout &lt;&lt; a &lt;&lt; endl;<br>cout &lt;&lt; p &lt;&lt; endl;<br>cout &lt;&lt; *p &lt;&lt; endl;</pre><p>Let us assume a fixed section of computer memory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/0*yeTnEb0HA8a3hMS5.PNG" /></figure><p>Suppose each segment in the memory is of 1 byte.</p><p>Now,</p><p>If a programmer types int x; in the program, the equivalent memory (4 Bytes) is allocated in the memory. When a *<em>pointer p</em> for x is created, the pointer points to integer x and *p stores the value of a whereas p stores the address of a.</p><h3>WHY DIFFERENT DATA TYPES FOR DIFFERENT POINTERS?</h3><p>It might strike that why do pointers have to be strongly typed when they only need to store addresses. The answer is pointers do a lot more than simply storing the addresses. Pointers are also used to dereference the addresses so that we can access and modify the values in these addresses.</p><h3>HOW ARE NUMBERS ACTUALLY STORED?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/0*UWk3gRAjclcdpuUE.PNG" /></figure><p>This is the binary representation of 1010</p><p>In modern-day compilers, an integer takes 4 bytes. The memory is byte-addressable.</p><p>The leftmost bit stores the information whether the integer is positive or negative. This bit is also called the **sign bit. **</p><pre>int a = 1010;<br>int *p=&amp;a;</pre><p>if the value of p is printed, 202 is printed because the address of byte 0 is used to address the integer variable. Now, if we print *p, the machine understands that p is an integer pointer hence it has 4 bytes beginning with address 202. This is because different pointer data types are needed.</p><p>**NOTE: The way the information is stored for float, char, and different data types is different in memory. **</p><pre>#include &lt;stdio.h&gt;</pre><pre>int main()<br>{<br>    int a=1010;<br>    int *p;<br>    p=&amp;a;<br>    printf(&quot;Value of p is %d and value of *p is %d&quot;,p,*p);<br>    char *c;<br>    c=(char*)p;<br>    printf(&quot;Value of c is %d and value of *c is %d&quot;,c,*c);<br>}</pre><pre>/*OUTPUT:<br>Value of p is -629538260 and value of *p is 1010 Value of c is -629<br>538260 and value of *c is -14                                     <br>                                                                  <br>...Program finished with exit code 0                              <br>Press ENTER to exit console.  */</pre><p>This happens because char is allocated one byte in memory, once the char pointer points to the typecasted integer it only takes the leftmost byte i.e. Least Significant Byte (LSB) and since it is char so does not extend to check memory for 4 next bytes and outputs decimal equivalent of LSB of binary 1010.</p><h3>Void Pointer:</h3><p>A void pointer is a generic pointer type that does not correspond to any particular data type and thus is called the void. A void pointer can not be dereferenced i.e. * can not be used with a void pointer</p><p>e.g:</p><pre>int a=1010;<br>void *v;<br>v= &amp;a;<br>int *p;<br>p=&amp;a;<br>v=p //Correct <br>printf(&quot;%d&quot;, v*); //Incorrect Because Void Pointer can not be dereferenced.</pre><h3>Pointer to Pointer Concept:</h3><p>It was made clear in the previous text that pointers are strongly typed. A pointer can point to a memory location that contains the corresponding data type.</p><pre>int a;<br>int *p;<br>p=&amp;a;</pre><p>But there’s an interesting fact that a pointer can point to another pointer variable. It is represented using double asterisk **.</p><pre>int a;<br>int *p;<br>p=&amp;a;<br>int **q;<br>q=&amp;p;</pre><h3>USE CASES:</h3><h3>As Function Arguments (Call By Reference):</h3><p>Memory is reserved for a program in execution and it is split as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/197/0*ZbMEhUj6TsBo8XWg.PNG" /></figure><p>These portions in memory describe the type of data they hold during the execution of the program. Out of these Stack, Static/Global and Code(Text) are fixed whereas Heap is resizable during the execution of the program.</p><p>Codes stores all the instructions. This includes declarations and statements. The static and global variables deal with a specific memory assigned. The local variables and methods are stored in the Stack.</p><p>Suppose there’s a program,</p><pre>#include &lt;stdio.h&gt;<br>void increment(int a)<br>{<br>a=a+1;<br>}<br>int main()<br>{<br>int a;<br>a=10;<br>increment(a);<br>printf(&quot;%d&quot;,a);<br>}</pre><p>The program intends to increase the value of a variable named a but it outputs 10 and does not show the incremented value.</p><p>This is because:</p><p>When the program is in execution, at first main method is triggered so all the information associated with the main function is stored in the stack. This information typically includes the local variables, returning to which function, etc. So, some part of stack memory is occupied with information about the main function, which is called a stack frame. Each function has a stack frame in the stack.</p><p>When the main function calls increment function, the execution of the main function is stopped for some time and the control is passed to the called function. Now, another stack frame is created for increment function. In this stack frame, local variables related to increment function are created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/0*4HapkwYhSkDYFhZc.PNG" /></figure><p>The real problem was when the a=a+1 statement is called, the local variable pertaining to the stack frame of function increment gets incremented which only got the value of a from the main function as the argument. The value of a was copied to a local variable of increment function and the same got incremented and thus did not result in incrementing the local variable of the main function because the local variables are not accessible outside the stack frame.</p><p>Once the control is passed back to the main function, the stack frame created for increment function is cleared. This implies that the lifetime of a local variable is till the time the function is executing.</p><p>The above-described scenario is called Call By Value.</p><p>If we look from a different perspective called Call By Reference, The code would look like,</p><pre>#include &lt;stdio.h&gt;<br>int increment( int *p)<br>{ *p= (*p)+1;<br>}<br>int main()<br>{<br>int a;<br>a=10;<br>increment(&amp;a);<br>printf(&quot;%d&quot;, a); //Prints 11<br>}</pre><p>While executing the value which is stored in the local variable p ( for function increment) is the address of memory location where a ( of function main) is stored, Hence the value of a is incremented using call By reference.</p><h3>Concept of Array and Pointers:</h3><p>When talking about an array, the concept of pointers is very crucial.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/0*L7-4Hq1TLGvoanHU.PNG" /></figure><p>Suppose the array named A is allocated memory as shown above. Since one integer takes 4 bytes the address of next integer will be 4 bytes more than the previous address.</p><p>int a= { 2 , 4 , 6 , 8 , 10 }</p><p>To print the address of the initial element we can print &amp;a[0] or we can also print the name of the array. To print the initial value *a can be used and for every subsequent value *(a + 1)</p><pre>#include &lt;stdio.h&gt;<br>int main()<br>{<br>    int a[]= {2,4,6,8,10};<br>    printf(&quot;Array is: { 2 , 4 , 6 , 8 , 10 } \n&quot;); <br>    printf(&quot;First Address Using printing &amp;a[0]: %d \n&quot;,&amp;a[0]);<br>    printf(&quot;First Address Using printing a :%d \n&quot;,a);<br>    printf(&quot;Value at First Address Using *&amp;a[0] is : %d \n&quot;,*&amp;a[0]);<br>    printf(&quot;Value at First Address Using *a is : %d \n&quot;,*a);<br>    printf(&quot;Value at First Address Using *(a+1) is : %d \n&quot;,*(a+1));<br>}</pre><h3>An array as Function Argument</h3><p>Pointer has a role to play when the array is passed as a function argument.</p><p>e.g. To print the sum of an array, the code can be like</p><pre>#include &lt;stdio.h&gt;<br>int calculateSum(int a[], int n){<br>    int i,sum;<br>    for(i=0;i&lt;n;++i){<br>        sum+=a[i];<br>    }<br>    return sum;<br>}<br>int main()<br>{<br>    int a[]= {2,4,6,8,10};<br>    int n=sizeof(a)/sizeof(a[0]);<br>    int sum=calculateSum(a,n);<br>    printf(&quot;%d&quot;,sum);<br>}</pre><p>This code calls calculateSum function from main and passes the array and size of the array to it. It calculates the sum and outputs 30.</p><p>But if we wanted to calculate the size of the array in the function calculateSum(), the code would look like,</p><pre>#include &lt;stdio.h&gt;<br>int calculateSum(int a[]){<br>    int i,sum;<br>    int n=sizeof(a)/sizeof(a[0]);<br>    printf(&quot;%d \n&quot;,n);<br>    for(i=0;i&lt;n;++i){<br>        sum+=a[i];<br>    }<br>    return sum;<br>}<br>int main()<br>{<br>    int a[]= {2,4,6,8,10};<br>    int sum=calculateSum(a);<br>    printf(&quot;%d&quot;,sum);<br>}</pre><p>But this outputs the incorrect sum</p><p>This is because whenever the array is passed as a function argument, the compiler understands it as a pointer to the first element of the array. This is done to save memory because arrays can be really large and to create a local array and copy content would require a large amount of memory in many cases. So the local memory created for the function calculateSum points to the array in the main function using a pointer.</p><h3>Pointers and Dynamic Memory</h3><p>Memory assigned to a program is divided into 4 segments as mentioned earlier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/0*AbPE4T4TO4CgE6w3.PNG" /></figure><p>There 4 segments of memory are used to store various components of a program. The memory assigned for stack, static/global and code segments can’t be changed during run time. When we talk about the stack, it is used for the local storage while the program is running.</p><p>When a function is called, a stack frame is allocated for the function and the required memory is assigned. The most recent called function sits on top of the stack and after the function is done processing, the stack frame is cleared.</p><p><em>The memory for the stack is assigned by the operating system but the actual allocation of memory for each function (the local variables etc. for the function) happens during the runtime.</em></p><p>If the number of functions is too many or by any other reason the memory assigned to the stack if totally utilized, it is called Stack Overflow.</p><p>One of the common examples of stack overflow is when the recursion goes infinitely.</p><p>The allocation and deallocation of memory in the stack happen by a set rule, When a function is called it is pushed on the top of the stack and when it finishes execution it is popped out from the stack. The scope of the variable does not change when the function is in the stack.</p><p>Example for Demonstration:</p><pre>#include &lt;stdio.h&gt;<br>int total;<br>int Square(int x)<br>{<br>return x*x;<br>}<br>int SquareOfSum(int x , int y)<br>{<br>int z = Square(x+y);<br>return z;<br>}<br>int main()<br>{<br>int a= 4, b= 8;<br>total=SquareOfSum(a,b);<br>printf(&quot;Output = %d&quot; , total);<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/0*yWk75t3vHbQmezxJ.PNG" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/0*kWIhgZbyIwT53TKv.png" /></figure><p>Most Recently Called Function Sits on Top of the stack and is also the one to be popped first.</p><p>PHASE 1: main() is called and the program begins.</p><p>PHASE 2: main() calls SumOfSquares()</p><p>PHASE 3: SumOfSquares() calls Square()</p><p>PHASE 4: Square returns value and memory for Square() is deallocated</p><p>PHASE 5: Control is passed back to the main</p><p>PHASE 6: Program finishes, main() is popped of stack and stack memory is empty</p><h3>Heap:</h3><p>Unlike the stack and other segments, the memory for the heap is not fixed. Its size can change during the run time. Also, there is no set rule for memory allocation and deallocation ( like push and pop in the stack).</p><p>A programmer can decide the amount of memory to be used and the duration for which the memory has to be used. A heap can grow as long as the system does not run out of memory.</p><p><em>Note: When talking about a memory associated with heap or stack, it is always referred to as the Random Access Memory.</em></p><p>Heap is also called a free pool of memory. The actual implementation of the heap is complex and varies from system to system, but the abstract view of the heap can be seen as a free pool of memory.</p><p>Heap is also called dynamic memory. Using heap is also called dynamic memory allocation.</p><p><em>NOTE: The term “Heap” is also used to denote a data structure but when talking about memory, it does not refer to the “Heap” as used in data structures. Although the data structure “Stack” is the same in memory as in data structures. The implementation of the stack, the data structure is used in memory but in terms of the heap in memory, it only refers to a free pool of memory.</em></p><h3>Dynamic Memory Allocation In C:</h3><p>Dynamic Memory allocation in C is carried out using 4 functions</p><ol><li>malloc</li><li>calloc</li><li>realloc</li><li>free</li></ol><p>Dynamic Memory Allocation in C++ is carried out using 2 operators</p><ol><li>new</li><li>delete</li></ol><p><em>Note: Since C++ has backward compatibility, the functions of C can also be used in C++.</em></p><p>C Program for Dynamic Memory Allocation:</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;stdlib.h&gt;<br>int main()<br>{<br>int a; //Since it is a local variable, it goes to stack<br>int *p;<br>p = (int*) malloc (sizeof(int));<br>/* Malloc returns a void pointer to the starting address of the memory block assigned. We have to typecast because it returns void pointer */ <br>*p=10;<br>// free(p);<br>p= (int*) malloc(sizeof(int));<br>*p=20;<br>/* a new memory block to store 20 is assigned at some other address in heap and the previous is not cleared */<br>free(p);<br>p=(int*) malloc (20*sizeof(int));</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/0*RI49m0em-TYf1IUI.PNG" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/0*Bk322aI_rqV97tL6.PNG" /></figure><p>IMPORTANT POINTS:</p><ul><li>Memory in heap is not cleared when the pointer is changed, it needs to be cleared every time when the value/variable stored is not required</li><li>The malloc(size) function returns a void pointer to the address of the memory in a heap so the void pointer has to be converted to integer pointer for storing integer values.</li><li>To allocate memory for array in heap, the malloc function needs to be given the size of the array:</li><li>For integer: 4 * Number of Elements</li><li>For Character Array: 1 * Number of Elements</li><li>Assigning/Changing values in heap is only done using referencing i.e. obtaining a pointer to the address of heap and then assigning the value using an asterisk. ( *p =10 )</li></ul><h3>Dynamic Memory Allocation in C++</h3><p>In C++ the two operators used are New and Delete. They are used similar to malloc and free functions in C. The difference is they are typesafe which means that typecasting is not required.</p><p>Syntax:</p><pre>int *p;<br>p = new int;<br>*p = 10;<br>p= new int[20];<br>delete[] p;</pre><h3>Malloc, Calloc, Realloc, and Free in C</h3><h3>Malloc:</h3><p>** **Malloc is most frequently used function for dynamic memory allocation.</p><p>Definition: void* malloc( size_t size)</p><ul><li>It returns a void pointer which has to be typecasted</li><li>size_t means only positive number can be entered (unsigned)</li><li>Assignment can only be done using dereferencing (Using pointers)</li></ul><p>Syntax: int *p=(int*) malloc(sizeof(int));</p><h3>Calloc:</h3><p>Calloc is similar to malloc but takes in two parameters. The first argument is the number of elements of particular data type and second argument is the size of the data type.</p><p>Syntax:</p><pre>int *p = (int*) calloc(1,sizeof(int));</pre><p>Another difference between malloc and calloc is that malloc initializes the assigned memory location with some garbage values while calloc does not initialize the values.</p><h3>Calloc:</h3><p>If we already have a dynamic block of memory and we need to change the size of the memory, then realloc is used.</p><p>Syntax:</p><pre>int *p = (int*) realloc(void *ptr, size_t size);</pre><p>*ptr= Address of initial block.</p><h3>EXAMPLES:</h3><pre>#include &lt;stdio.h&gt;</pre><pre>int main()<br>{<br>  int n;<br>  scanf(&quot;%d&quot;,&amp;n);<br>  int *arr=(int*) malloc(n*sizeof(int));<br>  arr[0]=1;<br>  printf(&quot;%d&quot;,arr[0]);<br>}</pre><pre>#include &lt;stdio.h&gt;</pre><pre>int main()<br>{<br>  int *p;<br>  p=(int*)malloc(sizeof(int));<br>  *p=10;<br>  printf(&quot;%d&quot;,*p);<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd58d79974e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>