<?xml version='1.0' encoding='UTF-8'?><rss xmlns:atom="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/" xmlns:blogger="http://schemas.google.com/blogger/2008" xmlns:georss="http://www.georss.org/georss" xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr="http://purl.org/syndication/thread/1.0" version="2.0"><channel><atom:id>tag:blogger.com,1999:blog-3459284654925679524</atom:id><lastBuildDate>Sun, 22 Feb 2026 20:13:29 +0000</lastBuildDate><category>System Programming</category><category>Generic</category><category>Data Structures</category><category>Design Patterns</category><category>Networking</category><category>Strings</category><category>XML</category><category>Java</category><category>Sorting</category><category>Bitwise Operators</category><category>File Operations</category><category>Graphs</category><category>Packet Formats</category><category>Search Algorithm</category><category>Security</category><category>dynamic programming</category><category>natural language processing</category><category>space complexity</category><category>time complexity</category><category>Algorithmic solution</category><category>BFS</category><category>BST</category><category>Builder</category><category>Builder Design Pattern</category><category>C</category><category>C programming</category><category>C++</category><category>COM</category><category>Circular queue</category><category>Code implementation</category><category>Coin denomination</category><category>Component Object Model</category><category>Cracking piggy bank puzzle</category><category>DAG</category><category>DFS</category><category>Decorator Design Pattern</category><category>Dijkstra</category><category>Dijkstra Java implementation</category><category>FTP</category><category>FTP implementation in C</category><category>Factory Method Design Pattern</category><category>File transfer protocol</category><category>Functions</category><category>Java programming</category><category>KMP Algorithm</category><category>Knapsack problem algorithm</category><category>LCS problem</category><category>Libconfig</category><category>Map in C++</category><category>Memory</category><category>Money-saving challenge</category><category>NLP</category><category>Optimal change</category><category>Overloading</category><category>Polymorphism</category><category>Problem-solving</category><category>Quiver</category><category>Read configuration files</category><category>Recursive approach</category><category>SOAP</category><category>SSC 2018</category><category>SSC Adit card 2018</category><category>SSC Combined Graduate Level Examination 2012 Admit Card</category><category>SSC Exam 2018</category><category>Shortest Path Algorithm</category><category>Simplest Codings NLP</category><category>TST deletion</category><category>TST insertion</category><category>TST search</category><category>Ternary Search</category><category>Trie</category><category>Web Service</category><category>Xerces</category><category>abstract binary search tree</category><category>auto-suggestion</category><category>autocomplete</category><category>backtracking</category><category>bottom-up approach</category><category>data structure</category><category>decision making</category><category>dictionaries</category><category>efficiency</category><category>efficient string matching</category><category>facade design pattern</category><category>gSOAP</category><category>knapsack problem code</category><category>knuth-morris-pratt algorithm</category><category>lcs dynamic programming table</category><category>longest common subsequence algorithm</category><category>nlp in java</category><category>optimal solution</category><category>pattern preprocessing</category><category>prefix function</category><category>prefix search</category><category>reconstruction</category><category>search algorithms</category><category>sentiment analysis</category><category>sentiment analysis in java</category><category>std::map in c++</category><category>string algorithms</category><category>string storage</category><title>Simplest Codings</title><description>Unravel the complexities of coding with Simplest Codings! Dive into programming through clear explanations, practical examples, and bite-sized tutorials. Whether you&#39;re a beginner or a seasoned pro, find the tips and tricks you need to master your coding skills.</description><link>http://simplestcodings.blogspot.com/</link><managingEditor>noreply@blogger.com (Anonymous)</managingEditor><generator>Blogger</generator><openSearch:totalResults>79</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><item><guid isPermaLink="false">tag:blogger.com,1999:blog-3459284654925679524.post-3033406139618727176</guid><pubDate>Sat, 03 Feb 2024 18:33:00 +0000</pubDate><atom:updated>2024-02-04T01:06:46.914+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">natural language processing</category><category domain="http://www.blogger.com/atom/ns#">NLP</category><category domain="http://www.blogger.com/atom/ns#">nlp in java</category><category domain="http://www.blogger.com/atom/ns#">sentiment analysis</category><category domain="http://www.blogger.com/atom/ns#">sentiment analysis in java</category><category domain="http://www.blogger.com/atom/ns#">Simplest Codings NLP</category><title>Harnessing Sentiment Analysis with Java: A Step-by-Step Guide using NLP</title><description>&lt;p style=&quot;text-align: left;&quot;&gt;&lt;span style=&quot;font-family: helvetica;&quot;&gt;Sentiment analysis, a powerful application of Natural Language Processing (NLP), allows developers to gain insights into the emotions expressed in textual data. In this article, we&#39;ll explore how to perform sentiment analysis in Java using the Stanford NLP library. We&#39;ll guide you through setting up a Maven project, compiling the code, and running it with practical examples.&lt;/span&gt;&lt;/p&gt;&lt;h2 style=&quot;text-align: left;&quot;&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgaeHxpAjGH725n8m7ZbLzTWNuTOG4xQErmZF46TEI0fraee4ZIU5NvZWsGwLs1T32DCRLQe4aMGlxb-qE0CpLbWRb-UjXJmGcdBs-mNTzr0E3YJbYZHue4FAkK3Sj2ubKZiZTbVPQrwk90QbyY1zMEOcq-ZDsLA76gELLuwNmjEzBjm8rGXFg_msdsx1A/s512/sentimentanalysis.png&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;512&quot; data-original-width=&quot;512&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgaeHxpAjGH725n8m7ZbLzTWNuTOG4xQErmZF46TEI0fraee4ZIU5NvZWsGwLs1T32DCRLQe4aMGlxb-qE0CpLbWRb-UjXJmGcdBs-mNTzr0E3YJbYZHue4FAkK3Sj2ubKZiZTbVPQrwk90QbyY1zMEOcq-ZDsLA76gELLuwNmjEzBjm8rGXFg_msdsx1A/s16000/sentimentanalysis.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;span style=&quot;font-family: helvetica;&quot;&gt;&lt;br /&gt;&lt;/span&gt;&lt;/h2&gt;&lt;h2 style=&quot;text-align: left;&quot;&gt;&lt;span style=&quot;font-family: helvetica;&quot;&gt;Prerequisites&lt;/span&gt;&lt;/h2&gt;&lt;div&gt;&lt;span style=&quot;font-family: helvetica;&quot;&gt;Get IntelliJ Idea from&amp;nbsp;https://www.jetbrains.com/idea/download.&amp;nbsp;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span style=&quot;font-family: helvetica;&quot;&gt;You can skip this and use any other IDE as well. The steps for setting up a maven project will be different for each IDE.&lt;/span&gt;&lt;/div&gt;&lt;h2 style=&quot;text-align: left;&quot;&gt;
    &lt;span style=&quot;font-family: helvetica;&quot;&gt;Step 1: Create a New Project&lt;/span&gt;
&lt;/h2&gt;
&lt;div&gt;
    &lt;ul style=&quot;text-align: left;&quot;&gt;
        &lt;li&gt;
      &lt;span style=&quot;font-family: helvetica;&quot;&gt;Open IntelliJ IDEA and click on &quot;Create New Project.&quot;&amp;nbsp;&lt;/span&gt;
        &lt;/li&gt;
        &lt;li&gt;
      &lt;span style=&quot;font-family: helvetica;&quot;&gt;Choose &quot;Maven&quot; as the project type and click &quot;Next.&quot;&amp;nbsp;&lt;/span&gt;
        &lt;/li&gt;
        &lt;li&gt;
      &lt;span style=&quot;font-family: helvetica;&quot;&gt;Set the &quot;GroupId&quot; to com.simplestcodings and &quot;ArtifactId&quot; to
        SentimentAnalysis.&amp;nbsp;&lt;/span&gt;
        &lt;/li&gt;
        &lt;li&gt;
      &lt;span style=&quot;font-family: helvetica;&quot;&gt;Click &quot;Next&quot; and then &quot;Finish.&quot;&amp;nbsp;&lt;/span&gt;
        &lt;/li&gt;
    &lt;/ul&gt;
&lt;/div&gt;
&lt;div&gt;
    &lt;span style=&quot;font-family: helvetica;&quot;&gt;&lt;br /&gt;&lt;/span&gt;
&lt;/div&gt;
&lt;h2 style=&quot;text-align: left;&quot;&gt;
    &lt;span style=&quot;font-family: helvetica;&quot;&gt;Step 2: Add Dependencies&lt;/span&gt;
&lt;/h2&gt;
&lt;div&gt;
  &lt;span style=&quot;font-family: helvetica;&quot;&gt;Open the pom.xml file in the editor and replace the content with this &lt;/span&gt;section:
&lt;/div&gt;
&lt;div&gt;
  &lt;span style=&quot;font-family: helvetica;&quot;&gt;
      &lt;pre class=&quot;prettyprint&quot; style=&quot;text-align: left;&quot;&gt;&lt;code class=&quot;language-xml&quot;&gt;
&amp;lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&amp;gt;
&amp;lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot;
         xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
         xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&amp;gt;
    &amp;lt;modelVersion&amp;gt;4.0.0&amp;lt;/modelVersion&amp;gt;

    &amp;lt;groupId&amp;gt;com.simplestcodings&amp;lt;/groupId&amp;gt;
    &amp;lt;artifactId&amp;gt;nlp&amp;lt;/artifactId&amp;gt;
    &amp;lt;version&amp;gt;1.0-SNAPSHOT&amp;lt;/version&amp;gt;

    &amp;lt;properties&amp;gt;
        &amp;lt;maven.compiler.source&amp;gt;17&amp;lt;/maven.compiler.source&amp;gt;
        &amp;lt;maven.compiler.target&amp;gt;17&amp;lt;/maven.compiler.target&amp;gt;
        &amp;lt;project.build.sourceEncoding&amp;gt;UTF-8&amp;lt;/project.build.sourceEncoding&amp;gt;
    &amp;lt;/properties&amp;gt;

    &amp;lt;dependencies&amp;gt;
        &amp;lt;dependency&amp;gt;
            &amp;lt;groupId&amp;gt;edu.stanford.nlp&amp;lt;/groupId&amp;gt;
            &amp;lt;artifactId&amp;gt;stanford-corenlp&amp;lt;/artifactId&amp;gt;
            &amp;lt;version&amp;gt;4.5.6&amp;lt;/version&amp;gt;
        &amp;lt;/dependency&amp;gt;
        &amp;lt;dependency&amp;gt;
            &amp;lt;groupId&amp;gt;edu.stanford.nlp&amp;lt;/groupId&amp;gt;
            &amp;lt;artifactId&amp;gt;stanford-corenlp&amp;lt;/artifactId&amp;gt;
            &amp;lt;version&amp;gt;4.5.6&amp;lt;/version&amp;gt;
            &amp;lt;classifier&amp;gt;models&amp;lt;/classifier&amp;gt;
        &amp;lt;/dependency&amp;gt;
        &amp;lt;dependency&amp;gt;
            &amp;lt;groupId&amp;gt;org.slf4j&amp;lt;/groupId&amp;gt;
            &amp;lt;artifactId&amp;gt;slf4j-simple&amp;lt;/artifactId&amp;gt;
            &amp;lt;version&amp;gt;1.7.32&amp;lt;/version&amp;gt;
        &amp;lt;/dependency&amp;gt;
        &amp;lt;dependency&amp;gt;
            &amp;lt;groupId&amp;gt;org.projectlombok&amp;lt;/groupId&amp;gt;
            &amp;lt;artifactId&amp;gt;lombok&amp;lt;/artifactId&amp;gt;
            &amp;lt;version&amp;gt;1.18.30&amp;lt;/version&amp;gt;
            &amp;lt;scope&amp;gt;provided&amp;lt;/scope&amp;gt;
        &amp;lt;/dependency&amp;gt;
    &amp;lt;/dependencies&amp;gt;

&amp;lt;/project&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
    &lt;/span&gt;
    &lt;h2 style=&quot;text-align: left;&quot;&gt;
    &lt;span style=&quot;font-family: helvetica;&quot;&gt; Step 3: Create Project Structure&lt;/span&gt;
    &lt;/h2&gt;
&lt;/div&gt;
&lt;div&gt;
    &lt;ul style=&quot;text-align: left;&quot;&gt;
        &lt;li&gt;
      &lt;span style=&quot;font-family: helvetica;&quot;&gt;Right-click on the src directory in your project and choose &quot;New&quot;
          -&amp;gt; &quot;Package.&quot;&amp;nbsp;&lt;/span&gt;
        &lt;/li&gt;
        &lt;li&gt;
      &lt;span style=&quot;font-family: helvetica;&quot;&gt;Name it com.simplestcodings.&amp;nbsp;&lt;/span&gt;
        &lt;/li&gt;
        &lt;li&gt;
      &lt;span style=&quot;font-family: helvetica;&quot;&gt;Inside the com.simplestcodings package, create a new Java class named
        SentimentAnalysis.&amp;nbsp;&lt;/span&gt;
        &lt;/li&gt;
    &lt;/ul&gt;
&lt;/div&gt;
&lt;div&gt;
    &lt;span style=&quot;font-family: helvetica;&quot;&gt;&lt;br /&gt;&lt;/span&gt;
&lt;/div&gt;
&lt;h2 style=&quot;text-align: left;&quot;&gt;
    &lt;span style=&quot;font-family: helvetica;&quot;&gt;Step 4: Configure Properties&lt;/span&gt;
&lt;/h2&gt;
&lt;div&gt;
  &lt;span style=&quot;font-family: helvetica;&quot;&gt;Right-click on the src directory and create a new directory named
    resources. Inside the resources directory, create a file named
    application.properties with the following content:&lt;/span&gt;
&lt;/div&gt;
&lt;div&gt;
  &lt;span style=&quot;font-family: helvetica;&quot;&gt;
      &lt;pre class=&quot;prettyprint&quot;&gt;tokenize.whitespace=true
ssplit.eolonly=true
annotators = tokenize, ssplit, parse, sentiment
&lt;/pre&gt;
      &lt;div&gt;
        &lt;span style=&quot;font-family: helvetica;&quot;&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;&lt;/span&gt;
    &lt;h2 style=&quot;text-align: left;&quot;&gt;
    &lt;span style=&quot;font-family: helvetica;&quot;&gt; Step 5: Write Code&lt;/span&gt;
    &lt;/h2&gt;
&lt;/div&gt;
&lt;div&gt;
  &lt;span style=&quot;font-family: helvetica;&quot;&gt;Replace the contents of SentimentAnalysis.java with the code provided
      below&lt;br /&gt;&lt;/span&gt;
&lt;/div&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;&lt;code class=&quot;language-java&quot;&gt;
package com.simplestcodings;

import edu.stanford.nlp.ling.CoreAnnotations;
import edu.stanford.nlp.pipeline.Annotation;
import edu.stanford.nlp.pipeline.StanfordCoreNLP;
import edu.stanford.nlp.sentiment.SentimentCoreAnnotations;
import edu.stanford.nlp.util.CoreMap;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SentimentAnalysis {

    public static void main(String[] args) {
        // Initialize the Stanford NLP pipeline
        StanfordCoreNLP pipeline = new StanfordCoreNLP(&quot;application.properties&quot;);

        // Sample text for sentiment analysis
        String text = &quot;Simplest codings is the best place to learn and grow. I am glad to be here.&quot;;

        // Perform sentiment analysis
        String sentiment = getSentiment(text, pipeline);

        // Display the result
        log.info(&quot;Text: {}, Sentiment: {}&quot;,text, sentiment);

        // Another Sample text for sentiment analysis
        text = &quot;I hate this place. I am not coming back here again. I am very disappointed.&quot;;

        // Perform sentiment analysis
        sentiment = getSentiment(text, pipeline);

        // Display the result
        log.info(&quot;Text: {}, Sentiment: {}&quot;,text, sentiment);
    }

    private static String getSentiment(String text, StanfordCoreNLP pipeline) {
        // Create an Annotation object with the input text
        Annotation annotation = new Annotation(text);

        // Run all the NLP annotators on the text
        pipeline.annotate(annotation);

        // Extract the sentiment from the annotation
        CoreMap sentence = annotation.get(CoreAnnotations.SentencesAnnotation.class).get(0);
        String sentiment = sentence.get(SentimentCoreAnnotations.SentimentClass.class);

        return sentiment;
    }
}



&lt;/code&gt;&lt;/pre&gt;&lt;div&gt;
&lt;/div&gt;
&lt;h2 style=&quot;text-align: left;&quot;&gt;
  &lt;span style=&quot;font-family: helvetica;&quot;&gt;Step 6: Run the Code&lt;/span&gt;
&lt;/h2&gt;
&lt;div&gt;
  &lt;span style=&quot;font-family: helvetica;&quot;&gt;&lt;br /&gt;&lt;/span&gt;
&lt;/div&gt;
&lt;div&gt;
  &lt;span style=&quot;font-family: helvetica;&quot;&gt;Right-click on the SentimentAnalysis class and select &quot;Run
      SentimentAnalysis.main()&quot;. Observe the output in the Run console, which
      should display the sentiment of the provided text.&lt;br /&gt;&lt;br /&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/a/AVvXsEgj3qHNNVI3XbJKnbCpmxo9WB0Zk6rok9XdfAgpqWSpmVYbekyyNUMurGnkjtbId--IjlGu33xa-4at9zYAVAuEeu_kOsk66aUkTd9L6rDrNqQl2LFV6NEJnNpAy39bun7mxNmGVN8IS5plEdL_QO4eqmWwf1hN1xsn93tA_AO44heDMbSui_2f0ws2lLQ&quot; style=&quot;clear: left; float: left; margin-bottom: 1em; margin-right: 1em;&quot;&gt;&lt;img alt=&quot;Harnessing Sentiment Analysis with Java: A Step-by-Step Guide using NLP&quot; data-original-height=&quot;2050&quot; data-original-width=&quot;3456&quot; src=&quot;https://blogger.googleusercontent.com/img/a/AVvXsEgj3qHNNVI3XbJKnbCpmxo9WB0Zk6rok9XdfAgpqWSpmVYbekyyNUMurGnkjtbId--IjlGu33xa-4at9zYAVAuEeu_kOsk66aUkTd9L6rDrNqQl2LFV6NEJnNpAy39bun7mxNmGVN8IS5plEdL_QO4eqmWwf1hN1xsn93tA_AO44heDMbSui_2f0ws2lLQ=s16000&quot; title=&quot;Harnessing Sentiment Analysis with Java: A Step-by-Step Guide using NLP&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;br /&gt;&lt;/div&gt;&lt;br /&gt;&lt;br /&gt;&lt;/span&gt;
&lt;/div&gt;
&lt;div&gt;
  &lt;span style=&quot;font-family: helvetica;&quot;&gt;&lt;br /&gt;&lt;/span&gt;
&lt;/div&gt;
&lt;div&gt;
  &lt;span style=&quot;font-family: helvetica;&quot;&gt;&lt;br /&gt;&lt;/span&gt;
&lt;/div&gt;&lt;div&gt;&lt;span style=&quot;font-family: helvetica;&quot;&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span style=&quot;font-family: helvetica;&quot;&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span style=&quot;font-family: helvetica;&quot;&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span style=&quot;font-family: helvetica;&quot;&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span style=&quot;font-family: helvetica;&quot;&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span style=&quot;font-family: helvetica;&quot;&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span style=&quot;font-family: helvetica;&quot;&gt;&lt;br /&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
  &lt;span style=&quot;font-family: helvetica;&quot;&gt;You have successfully set up and run a sentiment analysis Java project
      using the Stanford NLP library in IntelliJ IDEA. Feel free to explore more
      examples and experiment with different texts to gain insights into the
      sentiment analysis capabilities of Java and NLP. Happy
      coding!&lt;/span&gt;
&lt;/div&gt;
</description><link>http://simplestcodings.blogspot.com/2024/02/harnessing-sentiment-analysis-with-java.html</link><author>noreply@blogger.com (Varun)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgaeHxpAjGH725n8m7ZbLzTWNuTOG4xQErmZF46TEI0fraee4ZIU5NvZWsGwLs1T32DCRLQe4aMGlxb-qE0CpLbWRb-UjXJmGcdBs-mNTzr0E3YJbYZHue4FAkK3Sj2ubKZiZTbVPQrwk90QbyY1zMEOcq-ZDsLA76gELLuwNmjEzBjm8rGXFg_msdsx1A/s72-c/sentimentanalysis.png" height="72" width="72"/><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-3459284654925679524.post-8613834655176647719</guid><pubDate>Wed, 20 Dec 2023 19:57:00 +0000</pubDate><atom:updated>2024-02-03T23:09:39.313+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">Algorithmic solution</category><category domain="http://www.blogger.com/atom/ns#">Code implementation</category><category domain="http://www.blogger.com/atom/ns#">Coin denomination</category><category domain="http://www.blogger.com/atom/ns#">Cracking piggy bank puzzle</category><category domain="http://www.blogger.com/atom/ns#">dynamic programming</category><category domain="http://www.blogger.com/atom/ns#">Java</category><category domain="http://www.blogger.com/atom/ns#">Java programming</category><category domain="http://www.blogger.com/atom/ns#">Money-saving challenge</category><category domain="http://www.blogger.com/atom/ns#">Optimal change</category><category domain="http://www.blogger.com/atom/ns#">Problem-solving</category><category domain="http://www.blogger.com/atom/ns#">Recursive approach</category><title> Cracking the Piggy Bank Puzzle: A Java Adventure in Dynamic Programming</title><description>&lt;p data-sourcepos=&quot;5:1-5:199&quot; style=&quot;background-color: white; color: #1f1f1f; font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px; margin: 24px 0px; white-space-collapse: preserve; word-break: break-word;&quot;&gt;Hey there, intrepid coders! Today, we&#39;re diving into a piggy bank heist… of the intellectual kind, of course! We&#39;ll be using a powerful technique called &lt;span face=&quot;&amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif&quot; style=&quot;background-color: white; color: #1f1f1f; font-size: 16px; white-space-collapse: preserve;&quot;&gt;Dynamic Programming (DP) &lt;/span&gt;&lt;span face=&quot;&amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif&quot; style=&quot;background-color: white; color: #1f1f1f; font-size: 16px; white-space-collapse: preserve;&quot;&gt;to crack the code of a mischievous piggy bank and unlock its hidden treasures. Buckle up, because this adventure requires both logic and a dash of mathematical magic.&lt;/span&gt;
&lt;/p&gt;
&lt;p data-sourcepos=&quot;5:1-5:199&quot; style=&quot;background-color: white; color: #1f1f1f; font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px; margin: 24px 0px; white-space-collapse: preserve; word-break: break-word;&quot;&gt;&lt;/p&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjBKPVRhoZOhqRxT4bEAjutaRqcxkVBZ8qCDYxJk8uVRh4ZdoIq_Qym60Yna8lDUdsYQiz3s-5tukqEJNAoOMo6bczcT4L5sulu3odhXpkJUjSS9YOC5C1g6J8wi2rs_gik-R1T1zOQhwVaP2WlmgYpttBH2a_tA3B0lqQA1PGBsa4uMu30IN-2mRIHd5E/s2260/piggy.png&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;1398&quot; data-original-width=&quot;2260&quot; height=&quot;376&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjBKPVRhoZOhqRxT4bEAjutaRqcxkVBZ8qCDYxJk8uVRh4ZdoIq_Qym60Yna8lDUdsYQiz3s-5tukqEJNAoOMo6bczcT4L5sulu3odhXpkJUjSS9YOC5C1g6J8wi2rs_gik-R1T1zOQhwVaP2WlmgYpttBH2a_tA3B0lqQA1PGBsa4uMu30IN-2mRIHd5E/w607-h376/piggy.png&quot; width=&quot;607&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;span style=&quot;font-family: helvetica;&quot;&gt;

Imagine a piggy bank with compartments numbered 1 to N. Each compartment holds a certain amount of coins. Your mission is to maximise the total coins you can collect by following these two rules:
&lt;/span&gt;&lt;p&gt;&lt;/p&gt;
&lt;ol data-sourcepos=&quot;7:1-9:0&quot; style=&quot;background-color: white; color: #1f1f1f; font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px; margin: 4px 0px; padding-inline-start: 36px;&quot;&gt;
  &lt;li data-sourcepos=&quot;7:1-7:127&quot; style=&quot;margin-bottom: 10px;&quot;&gt;
    You can only&amp;nbsp;start at compartment 1&amp;nbsp;and move&amp;nbsp;rightward,
    collecting all the coins in a compartment before proceeding.
  &lt;/li&gt;
  &lt;li data-sourcepos=&quot;8:1-9:0&quot; style=&quot;margin-bottom: 10px;&quot;&gt;
    You can either&amp;nbsp;skip a compartment&amp;nbsp;(earning you 0 coins)
    or&amp;nbsp;rob a compartment, but&amp;nbsp;robbing two consecutive compartments is
    forbidden.
  &lt;/li&gt;
&lt;/ol&gt;
&lt;p data-sourcepos=&quot;10:1-10:301&quot; style=&quot;background-color: white; color: #1f1f1f; font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px; margin: 24px 0px; white-space-collapse: preserve; word-break: break-word;&quot;&gt;
This might seem tricky, but DP comes to the rescue! It breaks down the problem into smaller, overlapping subproblems and cleverly stores the solutions, saving you from redundant calculations. Think of it like mapping a treasure hunt – each solution to a subproblem guides you towards the bigger prize.
&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;&lt;code class=&quot;language-java&quot;&gt;
class PiggyBankBreaker {

    private final int[] coins; // Array storing coins in each compartment (1-indexed)
    private final int[] maxCoins; // DP array to store max achievable coins at each position (0-indexed)

    public PiggyBankBreaker(int[] coins) {
        this.coins = coins; // Copy original coin values
        this.maxCoins = new int[coins.length + 1]; // Allocate DP array with space for starting point (index 0)
    }

    public int crackPiggyBank() {
        // Base case: No coins at starting point
        maxCoins[0] = 0;

        // Loop through each compartment from index 1 (inclusive)
        for (int i = 1; i &amp;lt;= coins.length; i++) {
            // Option 1: Rob current compartment + max from 2 positions back (non-consecutive)
            int robCurrent;

            // Check if robbing current is even possible (avoid accessing coins[-1])
            if (i &amp;gt;= 3) {
                robCurrent = coins[i - 1] + maxCoins[i - 3];
            } else {
                // Default to skipping for initial positions where robbing isn&#39;t valid
                robCurrent = 0;
            }

            // Option 2: Skip current compartment and take max from previous position (consecutive)
            int skipCurrent = maxCoins[i - 1];

            // Choose the option that yields more coins
            maxCoins[i] = Math.max(robCurrent, skipCurrent);
        }

        // Return the maximum achievable coins from the last compartment
        return maxCoins[coins.length];
    }

    public static void main(String[] args) {
        // Example piggy bank with coins
        int[] coins = {2, 3, 1, 4, 5, 7, 10};

        PiggyBankBreaker breaker = new PiggyBankBreaker(coins);
        int maxLoot = breaker.crackPiggyBank();
        System.out.println(&quot;Maximum amount you can collect: &quot; + maxLoot);
    }
}&lt;/code&gt;&lt;/pre&gt;&lt;p data-sourcepos=&quot;3:1-3:74&quot; style=&quot;background-color: white; color: #1f1f1f; font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px; margin: 24px 0px; white-space-collapse: preserve; word-break: break-word;&quot;&gt;This Java code solves the piggy bank problem, where you maximise the coins collected while adhering to two rules:&lt;/p&gt;&lt;ol data-sourcepos=&quot;5:1-5:68&quot; style=&quot;background-color: white; color: #1f1f1f; font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px; margin: 4px 0px; padding-inline-start: 36px;&quot;&gt;&lt;li data-sourcepos=&quot;5:1-5:68&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Start at compartment 1 and move rightward, collecting all coins in each compartment.&lt;/li&gt;&lt;li data-sourcepos=&quot;6:1-7:0&quot; style=&quot;margin-bottom: 10px;&quot;&gt;You can either skip or rob a compartment, but not two consecutive compartments.&lt;/li&gt;&lt;/ol&gt;&lt;p data-sourcepos=&quot;8:1-8:114&quot; style=&quot;background-color: white; color: #1f1f1f; font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px; margin: 24px 0px; white-space-collapse: preserve; word-break: break-word;&quot;&gt;The code utilises Dynamic Programming (DP) to efficiently solve this problem by breaking it down into smaller, overlapping subproblems. Here&#39;s a breakdown of the key aspects:&lt;/p&gt;&lt;ul data-sourcepos=&quot;18:1-19:16&quot; style=&quot;background-color: white; color: #1f1f1f; font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px; margin: 4px 0px; padding-inline-start: 36px;&quot;&gt;&lt;li data-sourcepos=&quot;18:1-18:78&quot; style=&quot;margin-bottom: 10px;&quot;&gt;The method calculates the maximum coins achievable from any starting point.&lt;/li&gt;&lt;li data-sourcepos=&quot;19:1-19:16&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Base case:&amp;nbsp;&lt;code style=&quot;background-color: var(--bard-color-surface-container-high); border-radius: 6px; color: var(--bard-color-on-surface-variant); font-family: &amp;quot;Google Sans Mono&amp;quot;, monospace; font-size: 0.875rem; line-height: 1.25rem; padding: 1px 6px;&quot;&gt;maxCoins[0] = 0&lt;/code&gt;&amp;nbsp;since no coins are earned before starting.&lt;/li&gt;&lt;li data-sourcepos=&quot;20:1-20:66&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Loop:&amp;nbsp;Iterates through each compartment (index 1 to length).&lt;/li&gt;&lt;li data-sourcepos=&quot;21:1-24:100&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Rob current option:&lt;ul data-sourcepos=&quot;22:5-24:100&quot; style=&quot;margin: 4px 0px; padding-inline-start: 36px;&quot;&gt;&lt;li data-sourcepos=&quot;22:5-22:151&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Calculates&amp;nbsp;&lt;code style=&quot;background-color: var(--bard-color-surface-container-high); border-radius: 6px; color: var(--bard-color-on-surface-variant); font-family: &amp;quot;Google Sans Mono&amp;quot;, monospace; font-size: 0.875rem; line-height: 1.25rem; padding: 1px 6px;&quot;&gt;robCurrent&lt;/code&gt;&amp;nbsp;by adding the current coin value (&lt;code style=&quot;background-color: var(--bard-color-surface-container-high); border-radius: 6px; color: var(--bard-color-on-surface-variant); font-family: &amp;quot;Google Sans Mono&amp;quot;, monospace; font-size: 0.875rem; line-height: 1.25rem; padding: 1px 6px;&quot;&gt;coins[i - 1]&lt;/code&gt;) to the maximum coins achievable two positions back (&lt;code style=&quot;background-color: var(--bard-color-surface-container-high); border-radius: 6px; color: var(--bard-color-on-surface-variant); font-family: &amp;quot;Google Sans Mono&amp;quot;, monospace; font-size: 0.875rem; line-height: 1.25rem; padding: 1px 6px;&quot;&gt;maxCoins[i - 3]&lt;/code&gt;).&lt;/li&gt;&lt;li data-sourcepos=&quot;23:5-23:138&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Fix:&amp;nbsp;A conditional statement (&lt;code style=&quot;background-color: var(--bard-color-surface-container-high); border-radius: 6px; color: var(--bard-color-on-surface-variant); font-family: &amp;quot;Google Sans Mono&amp;quot;, monospace; font-size: 0.875rem; line-height: 1.25rem; padding: 1px 6px;&quot;&gt;i &amp;gt;= 3&lt;/code&gt;) ensures this calculation only happens for valid positions (avoiding&amp;nbsp;&lt;code style=&quot;background-color: var(--bard-color-surface-container-high); border-radius: 6px; color: var(--bard-color-on-surface-variant); font-family: &amp;quot;Google Sans Mono&amp;quot;, monospace; font-size: 0.875rem; line-height: 1.25rem; padding: 1px 6px;&quot;&gt;coins[-1]&lt;/code&gt;&amp;nbsp;access).&lt;/li&gt;&lt;li data-sourcepos=&quot;24:5-24:100&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Otherwise,&amp;nbsp;&lt;code style=&quot;background-color: var(--bard-color-surface-container-high); border-radius: 6px; color: var(--bard-color-on-surface-variant); font-family: &amp;quot;Google Sans Mono&amp;quot;, monospace; font-size: 0.875rem; line-height: 1.25rem; padding: 1px 6px;&quot;&gt;robCurrent&lt;/code&gt;&amp;nbsp;is set to 0,&amp;nbsp;mimicking skipping the compartment for initial positions.&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;li data-sourcepos=&quot;25:1-25:105&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Skip current option:&amp;nbsp;Simply takes the maximum coins from the previous position (&lt;code style=&quot;background-color: var(--bard-color-surface-container-high); border-radius: 6px; color: var(--bard-color-on-surface-variant); font-family: &amp;quot;Google Sans Mono&amp;quot;, monospace; font-size: 0.875rem; line-height: 1.25rem; padding: 1px 6px;&quot;&gt;maxCoins[i - 1]&lt;/code&gt;).&lt;/li&gt;&lt;li data-sourcepos=&quot;26:1-26:29&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Comparison:&amp;nbsp;Chooses the maximum value between&amp;nbsp;&lt;code style=&quot;background-color: var(--bard-color-surface-container-high); border-radius: 6px; color: var(--bard-color-on-surface-variant); font-family: &amp;quot;Google Sans Mono&amp;quot;, monospace; font-size: 0.875rem; line-height: 1.25rem; padding: 1px 6px;&quot;&gt;robCurrent&lt;/code&gt;&amp;nbsp;and&amp;nbsp;&lt;code style=&quot;background-color: var(--bard-color-surface-container-high); border-radius: 6px; color: var(--bard-color-on-surface-variant); font-family: &amp;quot;Google Sans Mono&amp;quot;, monospace; font-size: 0.875rem; line-height: 1.25rem; padding: 1px 6px;&quot;&gt;skipCurrent&lt;/code&gt;&amp;nbsp;and stores it in&amp;nbsp;&lt;code style=&quot;background-color: var(--bard-color-surface-container-high); border-radius: 6px; color: var(--bard-color-on-surface-variant); font-family: &amp;quot;Google Sans Mono&amp;quot;, monospace; font-size: 0.875rem; line-height: 1.25rem; padding: 1px 6px;&quot;&gt;maxCoins[i]&lt;/code&gt;.&amp;nbsp;This ensures the optimal decision is recorded for future subproblems.&lt;/li&gt;&lt;li data-sourcepos=&quot;27:1-28:0&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Final result:&amp;nbsp;The last element&amp;nbsp;&lt;code style=&quot;background-color: var(--bard-color-surface-container-high); border-radius: 6px; color: var(--bard-color-on-surface-variant); font-family: &amp;quot;Google Sans Mono&amp;quot;, monospace; font-size: 0.875rem; line-height: 1.25rem; padding: 1px 6px;&quot;&gt;maxCoins[coins.length]&lt;/code&gt;&amp;nbsp;represents the maximum achievable coins from the starting point (compartment 1).&lt;/li&gt;&lt;/ul&gt;</description><link>http://simplestcodings.blogspot.com/2023/12/cracking-piggy-bank-puzzle-java.html</link><author>noreply@blogger.com (Varun)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjBKPVRhoZOhqRxT4bEAjutaRqcxkVBZ8qCDYxJk8uVRh4ZdoIq_Qym60Yna8lDUdsYQiz3s-5tukqEJNAoOMo6bczcT4L5sulu3odhXpkJUjSS9YOC5C1g6J8wi2rs_gik-R1T1zOQhwVaP2WlmgYpttBH2a_tA3B0lqQA1PGBsa4uMu30IN-2mRIHd5E/s72-w607-h376-c/piggy.png" height="72" width="72"/><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-3459284654925679524.post-5580712275157911006</guid><pubDate>Wed, 20 Dec 2023 15:17:00 +0000</pubDate><atom:updated>2023-12-20T21:51:41.298+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">backtracking</category><category domain="http://www.blogger.com/atom/ns#">bottom-up approach</category><category domain="http://www.blogger.com/atom/ns#">lcs dynamic programming table</category><category domain="http://www.blogger.com/atom/ns#">LCS problem</category><category domain="http://www.blogger.com/atom/ns#">longest common subsequence algorithm</category><category domain="http://www.blogger.com/atom/ns#">optimal solution</category><category domain="http://www.blogger.com/atom/ns#">reconstruction</category><category domain="http://www.blogger.com/atom/ns#">space complexity</category><category domain="http://www.blogger.com/atom/ns#">string algorithms</category><category domain="http://www.blogger.com/atom/ns#">time complexity</category><title>Longest common subsequence in Java</title><description>&lt;div&gt;&lt;p data-sourcepos=&quot;3:1-3:20&quot; style=&quot;background-color: white; color: #1f1f1f; font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px; margin: 24px 0px; white-space-collapse: preserve; word-break: break-word;&quot;&gt;Longest Common Subsequence (LCS)&lt;/p&gt;&lt;span face=&quot;&amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif&quot; style=&quot;background-color: white; color: #1f1f1f; font-size: 16px;&quot;&gt;&lt;/span&gt;&lt;ul data-sourcepos=&quot;5:1-6:4&quot; style=&quot;background-color: white; color: #1f1f1f; font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px; margin: 4px 0px; padding-inline-start: 36px;&quot;&gt;&lt;li data-sourcepos=&quot;5:1-5:112&quot; style=&quot;margin-bottom: 10px;&quot;&gt;It&#39;s the longest sequence of characters that is present in the same relative order within two or more strings.&lt;/li&gt;&lt;li data-sourcepos=&quot;6:1-6:4&quot; style=&quot;margin-bottom: 10px;&quot;&gt;It doesn&#39;t have to be a contiguous substring; the characters can appear in different positions within the original strings.&lt;/li&gt;&lt;/ul&gt;&lt;div&gt;&lt;span face=&quot;Google Sans, Helvetica Neue, sans-serif&quot; style=&quot;color: #1f1f1f;&quot;&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span face=&quot;Google Sans, Helvetica Neue, sans-serif&quot; style=&quot;color: #1f1f1f;&quot;&gt;&lt;h3 style=&quot;background-color: white; font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px; margin: 24px 0px; text-align: left; white-space-collapse: preserve; word-break: break-word;&quot;&gt;Understanding the Problem&lt;/h3&gt;&lt;span style=&quot;background-color: white; font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px;&quot;&gt;&lt;/span&gt;&lt;ul data-sourcepos=&quot;5:1-5:9&quot; style=&quot;background-color: white; font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px; margin: 4px 0px; padding-inline-start: 36px;&quot;&gt;&lt;li data-sourcepos=&quot;5:1-5:9&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Imagine two strings,&amp;nbsp;written vertically on separate columns.&lt;/li&gt;&lt;li data-sourcepos=&quot;6:1-6:113&quot; style=&quot;margin-bottom: 10px;&quot;&gt;The goal is to find the longest sequence of characters that appears in the same order within both strings,&amp;nbsp;even if they&#39;re not consecutive.&lt;/li&gt;&lt;/ul&gt;&lt;span style=&quot;background-color: white; font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px;&quot;&gt;&lt;/span&gt;&lt;h3 style=&quot;background-color: white; font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px; margin: 24px 0px; text-align: left; white-space-collapse: preserve; word-break: break-word;&quot;&gt;Character Grid&lt;/h3&gt;&lt;span style=&quot;background-color: white; font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px;&quot;&gt;&lt;/span&gt;&lt;ul data-sourcepos=&quot;10:1-10:76&quot; style=&quot;background-color: white; font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px; margin: 4px 0px; padding-inline-start: 36px;&quot;&gt;&lt;li data-sourcepos=&quot;10:1-10:76&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Create a grid where each row represents a character from the first string,&amp;nbsp;and each column represents a character from the second string.&lt;/li&gt;&lt;li data-sourcepos=&quot;11:1-11:96&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Fill each cell with a color indicating whether the corresponding characters match (e.g.,&amp;nbsp;green) or not (e.g.,&amp;nbsp;white).&lt;/li&gt;&lt;/ul&gt;&lt;span style=&quot;background-color: white; font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px;&quot;&gt;&lt;/span&gt;&lt;h3 style=&quot;background-color: white; font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px; margin: 24px 0px; text-align: left; white-space-collapse: preserve; word-break: break-word;&quot;&gt;Tracing Paths&lt;/h3&gt;&lt;span style=&quot;background-color: white; font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px;&quot;&gt;&lt;/span&gt;&lt;ul data-sourcepos=&quot;15:1-19:0&quot; style=&quot;background-color: white; font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px; margin: 4px 0px; padding-inline-start: 36px;&quot;&gt;&lt;li data-sourcepos=&quot;15:1-15:43&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Start at the top-left corner of the grid.&lt;/li&gt;&lt;li data-sourcepos=&quot;16:1-16:70&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Move diagonally down-right only when characters match (green cells).&lt;/li&gt;&lt;li data-sourcepos=&quot;17:1-17:89&quot; style=&quot;margin-bottom: 10px;&quot;&gt;If characters don&#39;t match,&amp;nbsp;move either down or right to continue searching for matches.&lt;/li&gt;&lt;li data-sourcepos=&quot;18:1-19:0&quot; style=&quot;margin-bottom: 10px;&quot;&gt;The path you take represents the LCS.&lt;/li&gt;&lt;/ul&gt;&lt;span style=&quot;background-color: white; font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px;&quot;&gt;&lt;/span&gt;&lt;h3 style=&quot;background-color: white; font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px; margin: 24px 0px; text-align: left; white-space-collapse: preserve; word-break: break-word;&quot;&gt;Visualize the LCS&lt;/h3&gt;&lt;span style=&quot;background-color: white; font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px;&quot;&gt;&lt;/span&gt;&lt;ul data-sourcepos=&quot;22:1-24:0&quot; style=&quot;background-color: white; font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px; margin: 4px 0px; padding-inline-start: 36px;&quot;&gt;&lt;li data-sourcepos=&quot;22:1-22:75&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Highlight the cells along the longest path with a bolder color or border.&lt;/li&gt;&lt;li data-sourcepos=&quot;23:1-24:0&quot; style=&quot;margin-bottom: 10px;&quot;&gt;The characters in those cells,&amp;nbsp;read in order,&amp;nbsp;form the LCS.&lt;/li&gt;&lt;/ul&gt;&lt;span style=&quot;background-color: white; font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px;&quot;&gt;&lt;/span&gt;&lt;p data-sourcepos=&quot;25:1-25:12&quot; style=&quot;background-color: white; font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px; margin: 24px 0px; white-space-collapse: preserve; word-break: break-word;&quot;&gt;Example:&lt;/p&gt;&lt;span style=&quot;background-color: white; font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px;&quot;&gt;&lt;/span&gt;&lt;p data-sourcepos=&quot;27:1-27:40&quot; style=&quot;background-color: white; font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px; margin: 24px 0px; white-space-collapse: preserve; word-break: break-word;&quot;&gt;Consider strings &quot;AGGTAB&quot; and &quot;GXTXAYB&quot;:&lt;/p&gt;&lt;code-block _nghost-ng-c3283117893=&quot;&quot; class=&quot;&quot; ng-version=&quot;0.0.0-PLACEHOLDER&quot; style=&quot;background-color: white;&quot;&gt;&lt;div _ngcontent-ng-c3283117893=&quot;&quot; class=&quot;code-block ng-star-inserted&quot;&gt;&lt;pre _ngcontent-ng-c3283117893=&quot;&quot; style=&quot;margin-bottom: 0px; margin-top: 0px;&quot;&gt;&lt;code _ngcontent-ng-c3283117893=&quot;&quot; class=&quot;code-container no-decoration-radius&quot; role=&quot;text&quot; style=&quot;background-color: var(--bard-color-code-block-background); border-radius: 16px; color: var(--bard-color-on-surface-variant); direction: ltr; display: block; font-feature-settings: normal; font-kerning: auto; font-optical-sizing: auto; font-stretch: normal; font-variant-alternates: normal; font-variant-east-asian: normal; font-variant-numeric: normal; font-variant-position: normal; font-variation-settings: normal; line-height: 1.125rem; overflow-x: auto; padding: 16px;&quot;&gt;&lt;span style=&quot;font-family: Google Sans Mono, monospace;&quot;&gt;&lt;span style=&quot;font-size: 14px;&quot;&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgyGeQmWnmqPtVgIYCOc8eYi9W4uYudwsuX4G9EKkRfTOb4hM8j6QjrFw1V48a0zU1mWSs3jqzOBKDK3jlhW1CPWFg9DT0foGv62c-ikwLAUYgf-VxlY7T_h7cXQS3DeDLULxLgmGY4ZqVYutfzm6QTUqWhxXanx-tcOaXV2eCL4AND5qnlBPvgosaf-mE/s1826/LCS.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot; target=&quot;_blank&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;1619&quot; data-original-width=&quot;1826&quot; height=&quot;284&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgyGeQmWnmqPtVgIYCOc8eYi9W4uYudwsuX4G9EKkRfTOb4hM8j6QjrFw1V48a0zU1mWSs3jqzOBKDK3jlhW1CPWFg9DT0foGv62c-ikwLAUYgf-VxlY7T_h7cXQS3DeDLULxLgmGY4ZqVYutfzm6QTUqWhxXanx-tcOaXV2eCL4AND5qnlBPvgosaf-mE/s320/LCS.png&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;&lt;/div&gt;

&lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;font-family: Google Sans, Helvetica Neue, sans-serif;&quot;&gt;&lt;span style=&quot;font-size: 16px;&quot;&gt;LCS: &quot;GTAB&quot; (highlighted cells)&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/code-block&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;h3 style=&quot;background-color: white; color: #1f1f1f; font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px; margin: 24px 0px; text-align: left; white-space-collapse: preserve; word-break: break-word;&quot;&gt;Algorithm&lt;/h3&gt;&lt;span face=&quot;&amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif&quot; style=&quot;background-color: white; color: #1f1f1f; font-size: 16px;&quot;&gt;&lt;/span&gt;&lt;ol data-sourcepos=&quot;10:1-11:56&quot; style=&quot;background-color: white; color: #1f1f1f; font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px; margin: 4px 0px; padding-inline-start: 36px;&quot;&gt;&lt;li data-sourcepos=&quot;10:1-11:56&quot; style=&quot;margin-bottom: 10px;&quot;&gt;&lt;p data-sourcepos=&quot;10:4-10:33&quot; style=&quot;margin: 24px 0px; white-space-collapse: preserve; word-break: break-word;&quot;&gt;Dynamic Programming Table:&lt;/p&gt;&lt;ul data-sourcepos=&quot;11:4-13:0&quot; style=&quot;margin: 4px 0px; padding-inline-start: 36px;&quot;&gt;&lt;li data-sourcepos=&quot;11:4-11:108&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Create a 2D table&amp;nbsp;&lt;code style=&quot;background-color: var(--bard-color-surface-container-high); border-radius: 6px; color: var(--bard-color-on-surface-variant); font-family: &amp;quot;Google Sans Mono&amp;quot;, monospace; font-size: 0.875rem; line-height: 1.25rem; padding: 1px 6px;&quot;&gt;dp&lt;/code&gt;&amp;nbsp;with dimensions (m+1) x (n+1),&amp;nbsp;where m and n are the lengths of the two strings.&lt;/li&gt;&lt;li data-sourcepos=&quot;12:4-13:0&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Fill the first row and column with 0s,&amp;nbsp;indicating no LCS for empty strings.&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;li data-sourcepos=&quot;14:1-18:42&quot; style=&quot;margin-bottom: 10px;&quot;&gt;&lt;p data-sourcepos=&quot;14:4-14:25&quot; style=&quot;margin: 24px 0px; white-space-collapse: preserve; word-break: break-word;&quot;&gt;Filling the Table:&lt;/p&gt;&lt;ul data-sourcepos=&quot;15:4-18:42&quot; style=&quot;margin: 4px 0px; padding-inline-start: 36px;&quot;&gt;&lt;li data-sourcepos=&quot;15:4-15:57&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Iterate through the table,&amp;nbsp;starting from&amp;nbsp;&lt;code style=&quot;background-color: var(--bard-color-surface-container-high); border-radius: 6px; color: var(--bard-color-on-surface-variant); font-family: &amp;quot;Google Sans Mono&amp;quot;, monospace; font-size: 0.875rem; line-height: 1.25rem; padding: 1px 6px;&quot;&gt;dp[1][1]&lt;/code&gt;.&lt;/li&gt;&lt;li data-sourcepos=&quot;16:4-18:42&quot; style=&quot;margin-bottom: 10px;&quot;&gt;For each cell&amp;nbsp;&lt;code style=&quot;background-color: var(--bard-color-surface-container-high); border-radius: 6px; color: var(--bard-color-on-surface-variant); font-family: &amp;quot;Google Sans Mono&amp;quot;, monospace; font-size: 0.875rem; line-height: 1.25rem; padding: 1px 6px;&quot;&gt;dp[i][j]&lt;/code&gt;:&lt;ul data-sourcepos=&quot;17:6-18:42&quot; style=&quot;margin: 4px 0px; padding-inline-start: 36px;&quot;&gt;&lt;li data-sourcepos=&quot;17:6-18:42&quot; style=&quot;margin-bottom: 10px;&quot;&gt;If the characters at indices i-1 and j-1 in the strings match:&lt;ul data-sourcepos=&quot;18:8-18:42&quot; style=&quot;margin: 4px 0px; padding-inline-start: 36px;&quot;&gt;&lt;li data-sourcepos=&quot;18:8-18:42&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Set&amp;nbsp;&lt;code style=&quot;background-color: var(--bard-color-surface-container-high); border-radius: 6px; color: var(--bard-color-on-surface-variant); font-family: &amp;quot;Google Sans Mono&amp;quot;, monospace; font-size: 0.875rem; line-height: 1.25rem; padding: 1px 6px;&quot;&gt;dp[i][j] = dp[i-1][j-1] + 1&lt;/code&gt;&amp;nbsp;(add 1 to the LCS length of the previous substrings).&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;li data-sourcepos=&quot;19:6-21:0&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Else:&lt;ul data-sourcepos=&quot;20:8-21:0&quot; style=&quot;margin: 4px 0px; padding-inline-start: 36px;&quot;&gt;&lt;li data-sourcepos=&quot;20:8-21:0&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Set&amp;nbsp;&lt;code style=&quot;background-color: var(--bard-color-surface-container-high); border-radius: 6px; color: var(--bard-color-on-surface-variant); font-family: &amp;quot;Google Sans Mono&amp;quot;, monospace; font-size: 0.875rem; line-height: 1.25rem; padding: 1px 6px;&quot;&gt;dp[i][j] = max(dp[i-1][j], dp[i][j-1])&lt;/code&gt;&amp;nbsp;(take the maximum LCS length from the previous options).&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;li data-sourcepos=&quot;22:1-28:0&quot; style=&quot;margin-bottom: 10px;&quot;&gt;&lt;p data-sourcepos=&quot;22:4-22:30&quot; style=&quot;margin: 24px 0px; white-space-collapse: preserve; word-break: break-word;&quot;&gt;Reconstructing the LCS:&lt;/p&gt;&lt;ul data-sourcepos=&quot;23:4-28:0&quot; style=&quot;margin: 4px 0px; padding-inline-start: 36px;&quot;&gt;&lt;li data-sourcepos=&quot;23:4-23:66&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Start from the bottom-right corner of the table (&lt;code style=&quot;background-color: var(--bard-color-surface-container-high); border-radius: 6px; color: var(--bard-color-on-surface-variant); font-family: &amp;quot;Google Sans Mono&amp;quot;, monospace; font-size: 0.875rem; line-height: 1.25rem; padding: 1px 6px;&quot;&gt;dp[m][n]&lt;/code&gt;).&lt;/li&gt;&lt;li data-sourcepos=&quot;24:4-26:73&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Backtrack:&lt;ul data-sourcepos=&quot;25:6-26:73&quot; style=&quot;margin: 4px 0px; padding-inline-start: 36px;&quot;&gt;&lt;li data-sourcepos=&quot;25:6-25:118&quot; style=&quot;margin-bottom: 10px;&quot;&gt;If the characters at indices i-1 and j-1 match,&amp;nbsp;add the character to the LCS and move diagonally up (i--,&amp;nbsp;j--).&lt;/li&gt;&lt;li data-sourcepos=&quot;26:6-26:73&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Else,&amp;nbsp;move to the cell with the maximum value (either i-- or j--).&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;li data-sourcepos=&quot;27:4-28:0&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Reverse the constructed LCS string to get the correct order.&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;/ol&gt;&lt;/div&gt;&amp;nbsp;

&lt;pre class=&quot;prettyprint&quot;&gt;&lt;code class=&quot;language-java&quot;&gt;

public class LCS {

    public static String lcs(String str1, String str2) {
        int m = str1.length();
        int n = str2.length();

        int[][] dp = new int[m + 1][n + 1];

        // Build the table in a bottom-up manner
        for (int i = 1; i &amp;lt;= m; i++) {
            for (int j = 1; j &amp;lt;= n; j++) {
                if (str1.charAt(i - 1) == str2.charAt(j - 1)) {
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                } else {
                    dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
                }
            }
        }

        // Reconstruct the LCS
        StringBuilder lcs = new StringBuilder();
        int i = m, j = n;
        while (i &amp;gt; 0 &amp;amp;&amp;amp; j &amp;gt; 0) {
            if (str1.charAt(i - 1) == str2.charAt(j - 1)) {
                lcs.append(str1.charAt(i - 1));
                i--;
                j--;
            } else if (dp[i - 1][j] &amp;gt; dp[i][j - 1]) {
                i--;
            } else {
                j--;
            }
        }

        // Reverse the LCS string
        return lcs.reverse().toString();
    }

    // Example usage for testing
    public static void main(String[] args) {
        System.out.println(lcs(&quot;ABCDEFG&quot;, &quot;BCDGK&quot;));
        System.out.println(lcs(&quot;AGGTAB&quot;, &quot;GXTXAYB&quot;));
        System.out.println(lcs(&quot;ABCDE&quot;, &quot;A&quot;));
        System.out.println(lcs(&quot;A&quot;, &quot;BCDEF&quot;));
    }
}

&lt;/code&gt;
&lt;/pre&gt;
&lt;br /&gt;&lt;/div&gt;&lt;h3 style=&quot;text-align: left;&quot;&gt;&lt;span face=&quot;&amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif&quot; style=&quot;background-color: white; color: #1f1f1f; font-size: 16px; white-space-collapse: preserve;&quot;&gt;Explanation for code&lt;/span&gt;&lt;/h3&gt;&lt;div&gt;&lt;p data-sourcepos=&quot;3:1-3:20&quot; style=&quot;background-color: white; color: #1f1f1f; font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px; margin: 24px 0px; white-space-collapse: preserve; word-break: break-word;&quot;&gt;1. lcs() Method:&lt;/p&gt;&lt;span face=&quot;&amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif&quot; style=&quot;background-color: white; color: #1f1f1f; font-size: 16px;&quot;&gt;&lt;/span&gt;&lt;ul data-sourcepos=&quot;4:4-5:2&quot; style=&quot;background-color: white; color: #1f1f1f; font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px; margin: 4px 0px; padding-inline-start: 36px;&quot;&gt;&lt;li data-sourcepos=&quot;4:4-5:2&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Takes two strings as input.&lt;/li&gt;&lt;li data-sourcepos=&quot;5:4-5:75&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Uses dynamic programming to find the longest common subsequence (LCS).&lt;/li&gt;&lt;li data-sourcepos=&quot;6:4-7:0&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Returns the LCS string.&lt;/li&gt;&lt;/ul&gt;&lt;span face=&quot;&amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif&quot; style=&quot;background-color: white; color: #1f1f1f; font-size: 16px;&quot;&gt;&lt;/span&gt;&lt;h4 style=&quot;background-color: white; color: #1f1f1f; font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px; margin: 24px 0px; text-align: left; white-space-collapse: preserve; word-break: break-word;&quot;&gt;Steps&lt;/h4&gt;&lt;span face=&quot;&amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif&quot; style=&quot;background-color: white; color: #1f1f1f; font-size: 16px;&quot;&gt;&lt;/span&gt;&lt;ul data-sourcepos=&quot;10:4-11:24&quot; style=&quot;background-color: white; color: #1f1f1f; font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px; margin: 4px 0px; padding-inline-start: 36px;&quot;&gt;&lt;li data-sourcepos=&quot;10:4-10:91&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Create a DP Table:&amp;nbsp;Stores the lengths of LCSs for substrings of different lengths.&lt;/li&gt;&lt;li data-sourcepos=&quot;11:4-11:24&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Fill the DP Table:&lt;ul data-sourcepos=&quot;12:7-14:9&quot; style=&quot;margin: 4px 0px; padding-inline-start: 36px;&quot;&gt;&lt;li data-sourcepos=&quot;12:7-12:52&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Iterates through characters of both strings.&lt;/li&gt;&lt;li data-sourcepos=&quot;13:7-14:9&quot; style=&quot;margin-bottom: 10px;&quot;&gt;For each cell,&amp;nbsp;calculates the length of the LCS based on previous calculations:&lt;ul data-sourcepos=&quot;14:10-15:73&quot; style=&quot;margin: 4px 0px; padding-inline-start: 36px;&quot;&gt;&lt;li data-sourcepos=&quot;14:10-14:83&quot; style=&quot;margin-bottom: 10px;&quot;&gt;If characters match,&amp;nbsp;add 1 to the LCS length of the previous substrings.&lt;/li&gt;&lt;li data-sourcepos=&quot;15:10-15:73&quot; style=&quot;margin-bottom: 10px;&quot;&gt;If not,&amp;nbsp;take the maximum LCS length from the previous options.&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;li data-sourcepos=&quot;16:4-16:96&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Reconstruct the LCS:&amp;nbsp;Backtracks through the DP table to find the characters in the LCS.&lt;/li&gt;&lt;li data-sourcepos=&quot;17:4-18:0&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Reverse the LCS:&amp;nbsp;Since it&#39;s built backward,&amp;nbsp;reverse it before returning.&lt;/li&gt;&lt;/ul&gt;&lt;span face=&quot;&amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif&quot; style=&quot;background-color: white; color: #1f1f1f; font-size: 16px;&quot;&gt;&lt;/span&gt;&lt;h4 style=&quot;background-color: white; color: #1f1f1f; font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px; margin: 24px 0px; text-align: left; white-space-collapse: preserve; word-break: break-word;&quot;&gt;Take away points&lt;/h4&gt;&lt;span face=&quot;&amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif&quot; style=&quot;background-color: white; color: #1f1f1f; font-size: 16px;&quot;&gt;&lt;/span&gt;&lt;ul data-sourcepos=&quot;21:4-22:102&quot; style=&quot;background-color: white; color: #1f1f1f; font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px; margin: 4px 0px; padding-inline-start: 36px;&quot;&gt;&lt;li data-sourcepos=&quot;21:4-21:91&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Bottom-up approach:&amp;nbsp;Builds the solution from smaller subproblems to the final LCS.&lt;/li&gt;&lt;li data-sourcepos=&quot;22:4-22:102&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Dynamic programming principle:&amp;nbsp;Avoids redundant calculations by storing intermediate results.&lt;/li&gt;&lt;li data-sourcepos=&quot;23:4-23:66&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Time complexity:&amp;nbsp;O(mn),&amp;nbsp;where m and n are string lengths.&lt;/li&gt;&lt;li data-sourcepos=&quot;24:4-25:0&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Space complexity:&amp;nbsp;O(mn),&amp;nbsp;due to the DP table.&lt;/li&gt;&lt;/ul&gt;&lt;/div&gt;</description><link>http://simplestcodings.blogspot.com/2023/12/longest-common-subsequence-in-java.html</link><author>noreply@blogger.com (Varun)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgyGeQmWnmqPtVgIYCOc8eYi9W4uYudwsuX4G9EKkRfTOb4hM8j6QjrFw1V48a0zU1mWSs3jqzOBKDK3jlhW1CPWFg9DT0foGv62c-ikwLAUYgf-VxlY7T_h7cXQS3DeDLULxLgmGY4ZqVYutfzm6QTUqWhxXanx-tcOaXV2eCL4AND5qnlBPvgosaf-mE/s72-c/LCS.png" height="72" width="72"/><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-3459284654925679524.post-7150531635231867196</guid><pubDate>Wed, 20 Dec 2023 14:59:00 +0000</pubDate><atom:updated>2023-12-20T22:32:17.585+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">decision making</category><category domain="http://www.blogger.com/atom/ns#">dynamic programming</category><category domain="http://www.blogger.com/atom/ns#">Java</category><category domain="http://www.blogger.com/atom/ns#">Knapsack problem algorithm</category><category domain="http://www.blogger.com/atom/ns#">knapsack problem code</category><title> Knapsack Problem implementation in Java</title><description>&lt;div&gt;&lt;span face=&quot;&amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif&quot; style=&quot;background-color: white; color: #1f1f1f;&quot;&gt;&lt;p data-sourcepos=&quot;3:1-3:48&quot; style=&quot;font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px; margin: 24px 0px; text-align: left; white-space-collapse: preserve; word-break: break-word;&quot;&gt;Imagine a hiker&#39;s backpack (the knapsack) with limited space (capacity).&lt;/p&gt;&lt;span style=&quot;font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif;&quot;&gt;&lt;/span&gt;&lt;p data-sourcepos=&quot;5:1-5:101&quot; style=&quot;font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px; margin: 24px 0px; text-align: left; white-space-collapse: preserve; word-break: break-word;&quot;&gt;They have a collection of items, each with a value (usefulness) and a weight (space it occupies).&lt;/p&gt;&lt;span style=&quot;font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif;&quot;&gt;&lt;/span&gt;&lt;p data-sourcepos=&quot;7:1-7:120&quot; style=&quot;font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px; margin: 24px 0px; text-align: left; white-space-collapse: preserve; word-break: break-word;&quot;&gt;The goal is to fill the backpack with the most valuable combination of items, without exceeding its weight capacity.&lt;/p&gt;&lt;span style=&quot;font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif;&quot;&gt;&lt;/span&gt;&lt;h4 style=&quot;font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px; margin: 24px 0px; text-align: left; white-space-collapse: preserve; word-break: break-word;&quot;&gt;Visualizing the Items&lt;/h4&gt;&lt;span style=&quot;font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif;&quot;&gt;&lt;/span&gt;&lt;code-block _nghost-ng-c3283117893=&quot;&quot; class=&quot;&quot; ng-version=&quot;0.0.0-PLACEHOLDER&quot; style=&quot;font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px;&quot;&gt;&lt;div _ngcontent-ng-c3283117893=&quot;&quot; class=&quot;code-block ng-star-inserted&quot;&gt;&lt;pre _ngcontent-ng-c3283117893=&quot;&quot; style=&quot;margin-bottom: 0px; margin-top: 0px;&quot;&gt;&lt;code _ngcontent-ng-c3283117893=&quot;&quot; class=&quot;code-container no-decoration-radius&quot; role=&quot;text&quot; style=&quot;background-color: var(--bard-color-code-block-background); border-radius: 16px; color: var(--bard-color-on-surface-variant); direction: ltr; display: block; font-family: &amp;quot;Google Sans Mono&amp;quot;, monospace; font-feature-settings: normal; font-kerning: auto; font-optical-sizing: auto; font-size: 0.875rem; font-stretch: normal; font-variant-alternates: normal; font-variant-east-asian: normal; font-variant-numeric: normal; font-variant-position: normal; font-variation-settings: normal; line-height: 1.125rem; overflow-x: auto; padding: 16px;&quot;&gt;Item 1:  (value 60, weight 10)
Item 2:  (value 100, weight 20)
Item 3:  (value 120, weight 30)

&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi42EONRKkCLItUT8CdBXjHnDCDOUxH2ZZXRoFEc_-gqObYrPkCZeqpwA3ANztIzWxfwHhrs3gX4uY0ktkuDfntqyOCWQ-i_gCriHbmk0TApMSGUuyuFg6YJv9lC4hZDwnUTVu2Y5rPR_MlkKScdkuTO0dK8LsMdxiBWsBrs1Xv3ibl-OXrUtzqmOmJi_s/s776/Weights.png&quot; imageanchor=&quot;1&quot; style=&quot;clear: left; float: left; margin-bottom: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;263&quot; data-original-width=&quot;776&quot; height=&quot;232&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi42EONRKkCLItUT8CdBXjHnDCDOUxH2ZZXRoFEc_-gqObYrPkCZeqpwA3ANztIzWxfwHhrs3gX4uY0ktkuDfntqyOCWQ-i_gCriHbmk0TApMSGUuyuFg6YJv9lC4hZDwnUTVu2Y5rPR_MlkKScdkuTO0dK8LsMdxiBWsBrs1Xv3ibl-OXrUtzqmOmJi_s/w686-h232/Weights.png&quot; width=&quot;686&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/code-block&gt;&lt;span style=&quot;font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif;&quot;&gt;&lt;/span&gt;&lt;p data-sourcepos=&quot;17:1-17:17&quot; style=&quot;font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px; margin: 24px 0px; text-align: left; white-space-collapse: preserve; word-break: break-word;&quot;&gt;&lt;/p&gt;&lt;h4 style=&quot;font-size: 16px; text-align: left;&quot;&gt;The Knapsack&lt;/h4&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; font-size: 16px; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiR6k-BEQzeCrnoRvCZw75fpkIcr82yfr9yMAfMwPyaR319FtJ5kDTeo8yNgtDNReNGoM3UAtsaKFhc0QVVqGXA4r1VEN_jmeTFH7L3MVCaisyd9tI54hQhP1G_FQ83a2qXHRbjBw9n1a9O8uDp3tOdIc2oPt8cdb7ibuOIUB1r2Fy35whYeSF_660av0U/s1024/image.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;1024&quot; data-original-width=&quot;1024&quot; height=&quot;320&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiR6k-BEQzeCrnoRvCZw75fpkIcr82yfr9yMAfMwPyaR319FtJ5kDTeo8yNgtDNReNGoM3UAtsaKFhc0QVVqGXA4r1VEN_jmeTFH7L3MVCaisyd9tI54hQhP1G_FQ83a2qXHRbjBw9n1a9O8uDp3tOdIc2oPt8cdb7ibuOIUB1r2Fy35whYeSF_660av0U/s320/image.png&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;
&lt;p style=&quot;font-size: 16px; text-align: left;&quot;&gt;&lt;/p&gt;&lt;span style=&quot;font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif;&quot;&gt;&lt;/span&gt;&lt;h4 style=&quot;font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px; margin: 24px 0px; text-align: left; white-space-collapse: preserve; word-break: break-word;&quot;&gt;Decision-Making&lt;/h4&gt;&lt;span style=&quot;font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif;&quot;&gt;&lt;/span&gt;&lt;ul data-sourcepos=&quot;25:1-29:33&quot; style=&quot;margin: 4px 0px; padding-inline-start: 36px; text-align: left;&quot;&gt;&lt;li data-sourcepos=&quot;25:1-25:49&quot; style=&quot;font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px; margin-bottom: 10px;&quot;&gt;Can&#39;t fit all items directly (total weight 60).&lt;/li&gt;&lt;li&gt;&lt;span style=&quot;font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif;&quot;&gt;Optimal choice would be to put these items in the bag&lt;br /&gt;&lt;/span&gt;&lt;/li&gt;&lt;ul&gt;&lt;li&gt;&lt;span style=&quot;font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif;&quot;&gt;Item: {value: 120, weight: 30}&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span style=&quot;font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif;&quot;&gt;Item: {value: 100, weight: 20}&lt;/span&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/ul&gt;&lt;span style=&quot;font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif;&quot;&gt;&lt;/span&gt;&lt;h4 style=&quot;font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px; margin: 24px 0px; text-align: left; white-space-collapse: preserve; word-break: break-word;&quot;&gt;Optimal Solution&lt;/h4&gt;&lt;span style=&quot;font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif;&quot;&gt;&lt;/span&gt;&lt;code-block _nghost-ng-c3283117893=&quot;&quot; class=&quot;&quot; ng-version=&quot;0.0.0-PLACEHOLDER&quot; style=&quot;font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px;&quot;&gt;&lt;div _ngcontent-ng-c3283117893=&quot;&quot; class=&quot;code-block ng-star-inserted&quot;&gt;&lt;pre _ngcontent-ng-c3283117893=&quot;&quot; style=&quot;margin-bottom: 0px; margin-top: 0px;&quot;&gt;&lt;code _ngcontent-ng-c3283117893=&quot;&quot; class=&quot;code-container no-decoration-radius&quot; role=&quot;text&quot; style=&quot;background-color: var(--bard-color-code-block-background); border-radius: 16px; color: var(--bard-color-on-surface-variant); direction: ltr; display: block; font-family: &amp;quot;Google Sans Mono&amp;quot;, monospace; font-feature-settings: normal; font-kerning: auto; font-optical-sizing: auto; font-size: 0.875rem; font-stretch: normal; font-variant-alternates: normal; font-variant-east-asian: normal; font-variant-numeric: normal; font-variant-position: normal; font-variation-settings: normal; line-height: 1.125rem; overflow-x: auto; padding: 16px;&quot;&gt;KNAPSACK  (capacity 50)
     (value 120, weight 30)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/code-block&gt;&lt;span style=&quot;font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif;&quot;&gt;&lt;/span&gt;&lt;h4 style=&quot;font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px; margin: 24px 0px; text-align: left; white-space-collapse: preserve; word-break: break-word;&quot;&gt;Key Points&lt;/h4&gt;&lt;span style=&quot;font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif;&quot;&gt;&lt;/span&gt;&lt;ul data-sourcepos=&quot;40:1-43:58&quot; style=&quot;font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px; margin: 4px 0px; padding-inline-start: 36px; text-align: left;&quot;&gt;&lt;li data-sourcepos=&quot;40:1-40:63&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Knapsack represents a resource constraint (limited capacity).&lt;/li&gt;&lt;li data-sourcepos=&quot;41:1-41:74&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Items represent choices with associated values and constraints (weight).&lt;/li&gt;&lt;li data-sourcepos=&quot;42:1-42:50&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Goal is to maximize value within the constraint.&lt;/li&gt;&lt;li data-sourcepos=&quot;43:1-43:58&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Often involves trade-offs and strategic decision-making.&lt;/li&gt;&lt;/ul&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span face=&quot;&amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif&quot; style=&quot;background-color: white; color: #1f1f1f; font-size: 16px;&quot;&gt;&lt;br /&gt;&lt;span style=&quot;font-family: helvetica;&quot;&gt;In formal language, g&lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;background-color: white; color: #1f1f1f; font-size: 16px;&quot;&gt;&lt;span style=&quot;font-family: helvetica;&quot;&gt;iven a set of items,&amp;nbsp;each with a weight and a value,&amp;nbsp;and a knapsack with a maximum weight capacity,&amp;nbsp;find the subset of items that maximizes the total value while fitting within the weight capacity.&lt;/span&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;h3 style=&quot;background-color: white; color: #1f1f1f; font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px; margin: 24px 0px; text-align: left; white-space-collapse: preserve; word-break: break-word;&quot;&gt;Dynamic Programming Approach&lt;/h3&gt;&lt;span face=&quot;&amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif&quot; style=&quot;background-color: white; color: #1f1f1f; font-size: 16px;&quot;&gt;&lt;/span&gt;&lt;ol data-sourcepos=&quot;11:1-11:13&quot; style=&quot;background-color: white; color: #1f1f1f; font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px; margin: 4px 0px; padding-inline-start: 36px;&quot;&gt;&lt;li data-sourcepos=&quot;11:1-11:13&quot; style=&quot;margin-bottom: 10px;&quot;&gt;&lt;p data-sourcepos=&quot;11:4-11:27&quot; style=&quot;margin: 24px 0px; white-space-collapse: preserve; word-break: break-word;&quot;&gt;Create a table &lt;code style=&quot;background-color: var(--bard-color-surface-container-high); border-radius: 6px; color: var(--bard-color-on-surface-variant); font-family: &amp;quot;Google Sans Mono&amp;quot;, monospace; font-size: 0.875rem; line-height: 1.25rem; padding: 1px 6px;&quot;&gt;dp&lt;/code&gt;:&lt;/p&gt;&lt;ul data-sourcepos=&quot;12:4-14:0&quot; style=&quot;margin: 4px 0px; padding-inline-start: 36px;&quot;&gt;&lt;li data-sourcepos=&quot;12:4-12:104&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Dimensions:&amp;nbsp;&lt;code style=&quot;background-color: var(--bard-color-surface-container-high); border-radius: 6px; color: var(--bard-color-on-surface-variant); font-family: &amp;quot;Google Sans Mono&amp;quot;, monospace; font-size: 0.875rem; line-height: 1.25rem; padding: 1px 6px;&quot;&gt;(n + 1) x (W + 1)&lt;/code&gt;,&amp;nbsp;where&amp;nbsp;&lt;code style=&quot;background-color: var(--bard-color-surface-container-high); border-radius: 6px; color: var(--bard-color-on-surface-variant); font-family: &amp;quot;Google Sans Mono&amp;quot;, monospace; font-size: 0.875rem; line-height: 1.25rem; padding: 1px 6px;&quot;&gt;n&lt;/code&gt;&amp;nbsp;is the number of items and&amp;nbsp;&lt;code style=&quot;background-color: var(--bard-color-surface-container-high); border-radius: 6px; color: var(--bard-color-on-surface-variant); font-family: &amp;quot;Google Sans Mono&amp;quot;, monospace; font-size: 0.875rem; line-height: 1.25rem; padding: 1px 6px;&quot;&gt;W&lt;/code&gt;&amp;nbsp;is the knapsack capacity.&lt;/li&gt;&lt;li data-sourcepos=&quot;13:4-14:0&quot; style=&quot;margin-bottom: 10px;&quot;&gt;&lt;code style=&quot;background-color: var(--bard-color-surface-container-high); border-radius: 6px; color: var(--bard-color-on-surface-variant); font-family: &amp;quot;Google Sans Mono&amp;quot;, monospace; font-size: 0.875rem; line-height: 1.25rem; padding: 1px 6px;&quot;&gt;dp[i][w]&lt;/code&gt;&amp;nbsp;stores the maximum value achievable using items up to the&amp;nbsp;&lt;code style=&quot;background-color: var(--bard-color-surface-container-high); border-radius: 6px; color: var(--bard-color-on-surface-variant); font-family: &amp;quot;Google Sans Mono&amp;quot;, monospace; font-size: 0.875rem; line-height: 1.25rem; padding: 1px 6px;&quot;&gt;i-th&lt;/code&gt;&amp;nbsp;item and with a maximum weight of&amp;nbsp;&lt;code style=&quot;background-color: var(--bard-color-surface-container-high); border-radius: 6px; color: var(--bard-color-on-surface-variant); font-family: &amp;quot;Google Sans Mono&amp;quot;, monospace; font-size: 0.875rem; line-height: 1.25rem; padding: 1px 6px;&quot;&gt;w&lt;/code&gt;.&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;li data-sourcepos=&quot;15:1-19:5&quot; style=&quot;margin-bottom: 10px;&quot;&gt;&lt;p data-sourcepos=&quot;15:4-15:22&quot; style=&quot;margin: 24px 0px; white-space-collapse: preserve; word-break: break-word;&quot;&gt;Fill the table:&lt;/p&gt;&lt;ul data-sourcepos=&quot;16:4-19:5&quot; style=&quot;margin: 4px 0px; padding-inline-start: 36px;&quot;&gt;&lt;li data-sourcepos=&quot;16:4-18:69&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Base cases:&lt;ul data-sourcepos=&quot;17:6-18:69&quot; style=&quot;margin: 4px 0px; padding-inline-start: 36px;&quot;&gt;&lt;li data-sourcepos=&quot;17:6-17:57&quot; style=&quot;margin-bottom: 10px;&quot;&gt;&lt;code style=&quot;background-color: var(--bard-color-surface-container-high); border-radius: 6px; color: var(--bard-color-on-surface-variant); font-family: &amp;quot;Google Sans Mono&amp;quot;, monospace; font-size: 0.875rem; line-height: 1.25rem; padding: 1px 6px;&quot;&gt;dp[0][w] = 0&lt;/code&gt;&amp;nbsp;for all&amp;nbsp;&lt;code style=&quot;background-color: var(--bard-color-surface-container-high); border-radius: 6px; color: var(--bard-color-on-surface-variant); font-family: &amp;quot;Google Sans Mono&amp;quot;, monospace; font-size: 0.875rem; line-height: 1.25rem; padding: 1px 6px;&quot;&gt;w&lt;/code&gt;&amp;nbsp;(no items,&amp;nbsp;value is 0).&lt;/li&gt;&lt;li data-sourcepos=&quot;18:6-18:69&quot; style=&quot;margin-bottom: 10px;&quot;&gt;&lt;code style=&quot;background-color: var(--bard-color-surface-container-high); border-radius: 6px; color: var(--bard-color-on-surface-variant); font-family: &amp;quot;Google Sans Mono&amp;quot;, monospace; font-size: 0.875rem; line-height: 1.25rem; padding: 1px 6px;&quot;&gt;dp[i][0] = 0&lt;/code&gt;&amp;nbsp;for all&amp;nbsp;&lt;code style=&quot;background-color: var(--bard-color-surface-container-high); border-radius: 6px; color: var(--bard-color-on-surface-variant); font-family: &amp;quot;Google Sans Mono&amp;quot;, monospace; font-size: 0.875rem; line-height: 1.25rem; padding: 1px 6px;&quot;&gt;i&lt;/code&gt;&amp;nbsp;(zero weight capacity,&amp;nbsp;value is 0).&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;li data-sourcepos=&quot;19:4-19:5&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Recursive formula:&lt;ul data-sourcepos=&quot;20:6-23:0&quot; style=&quot;margin: 4px 0px; padding-inline-start: 36px;&quot;&gt;&lt;li data-sourcepos=&quot;20:6-21:62&quot; style=&quot;margin-bottom: 10px;&quot;&gt;&lt;code style=&quot;background-color: var(--bard-color-surface-container-high); border-radius: 6px; color: var(--bard-color-on-surface-variant); font-family: &amp;quot;Google Sans Mono&amp;quot;, monospace; font-size: 0.875rem; line-height: 1.25rem; padding: 1px 6px;&quot;&gt;dp[i][w] = max(dp[i-1][w], value[i] + dp[i-1][w-weight[i]])&lt;/code&gt;&amp;nbsp;if&amp;nbsp;&lt;code style=&quot;background-color: var(--bard-color-surface-container-high); border-radius: 6px; color: var(--bard-color-on-surface-variant); font-family: &amp;quot;Google Sans Mono&amp;quot;, monospace; font-size: 0.875rem; line-height: 1.25rem; padding: 1px 6px;&quot;&gt;weight[i] &amp;lt;= w&lt;/code&gt;&amp;nbsp;(Choose between including or excluding the&amp;nbsp;&lt;code style=&quot;background-color: var(--bard-color-surface-container-high); border-radius: 6px; color: var(--bard-color-on-surface-variant); font-family: &amp;quot;Google Sans Mono&amp;quot;, monospace; font-size: 0.875rem; line-height: 1.25rem; padding: 1px 6px;&quot;&gt;i-th&lt;/code&gt;&amp;nbsp;item)&lt;/li&gt;&lt;li data-sourcepos=&quot;22:6-23:0&quot; style=&quot;margin-bottom: 10px;&quot;&gt;&lt;code style=&quot;background-color: var(--bard-color-surface-container-high); border-radius: 6px; color: var(--bard-color-on-surface-variant); font-family: &amp;quot;Google Sans Mono&amp;quot;, monospace; font-size: 0.875rem; line-height: 1.25rem; padding: 1px 6px;&quot;&gt;dp[i][w] = dp[i-1][w]&lt;/code&gt;&amp;nbsp;otherwise (Item cannot be included due to weight constraint)&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;li data-sourcepos=&quot;24:1-27:0&quot; style=&quot;margin-bottom: 10px;&quot;&gt;&lt;p data-sourcepos=&quot;24:4-24:16&quot; style=&quot;margin: 24px 0px; white-space-collapse: preserve; word-break: break-word;&quot;&gt;Solution:&lt;/p&gt;&lt;/li&gt;&lt;ul data-sourcepos=&quot;25:4-27:0&quot; style=&quot;margin: 4px 0px; padding-inline-start: 36px;&quot;&gt;&lt;li data-sourcepos=&quot;25:4-25:82&quot; style=&quot;margin-bottom: 10px;&quot;&gt;The maximum value is&amp;nbsp;&lt;code style=&quot;background-color: var(--bard-color-surface-container-high); border-radius: 6px; color: var(--bard-color-on-surface-variant); font-family: &amp;quot;Google Sans Mono&amp;quot;, monospace; font-size: 0.875rem; line-height: 1.25rem; padding: 1px 6px;&quot;&gt;dp[n][W]&lt;/code&gt;&amp;nbsp;(using all items with the knapsack capacity).&lt;/li&gt;&lt;li data-sourcepos=&quot;26:4-27:0&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Backtrack to find the selected items.&lt;/li&gt;&lt;/ul&gt;&lt;/ol&gt;&lt;div&gt;&lt;span face=&quot;Google Sans, Helvetica Neue, sans-serif&quot; style=&quot;color: #1f1f1f;&quot;&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div&gt;&lt;span face=&quot;Google Sans, Helvetica Neue, sans-serif&quot; style=&quot;color: #1f1f1f;&quot;&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;


&lt;pre class=&quot;prettyprint&quot;&gt;&lt;code class=&quot;language-java&quot;&gt;
import java.util.ArrayList;
import java.util.List;

public class Knapsack {

    public static List&lt;item&gt; knapsack(List&lt;item&gt; items, int capacity) {
        int[][] dp = new int[items.size() + 1][capacity + 1];

        // Build table dp[][] in a bottom-up manner
        for (int i = 0; i &amp;lt;= items.size(); i++) {
            for (int w = 0; w &amp;lt;= capacity; w++) {
                if (i == 0 || w == 0) {
                    dp[i][w] = 0;
                } else if (items.get(i - 1).weight &amp;lt;= w) {
                    dp[i][w] = Math.max(items.get(i - 1).value + dp[i - 1][w - items.get(i - 1).weight], dp[i - 1][w]);
                } else {
                    dp[i][w] = dp[i - 1][w];
                }
            }
        }

        // Reconstruct the solution
        List&lt;item&gt; selectedItems = new ArrayList&amp;lt;&amp;gt;();
        int i = items.size(), w = capacity;
        while (i &amp;gt; 0 &amp;amp;&amp;amp; w &amp;gt; 0) {
            if (dp[i][w] != dp[i - 1][w]) {
                selectedItems.add(items.get(i - 1));
                w -= items.get(i - 1).weight;
            }
            i--;
        }

        return selectedItems;
    }

    public static void main(String[] args) {
        List&lt;item&gt; items = new ArrayList&amp;lt;&amp;gt;();
        items.add(new Item(60, 10));
        items.add(new Item(100, 20));
        items.add(new Item(120, 30));
        int capacity = 50;

        List&lt;item&gt; selected = knapsack(items, capacity);
        System.out.println(&quot;Selected items: &quot; + selected);
    }

    public static class Item {
        int value;
        int weight;

        Item(int value, int weight) {
            this.value = value;
            this.weight = weight;
        }

        @Override
        public String toString() {
            return &quot;Item: {value: &quot; + value + &quot;, weight: &quot; + weight + &quot;}&quot;;
        }
    }
}

&lt;/item&gt;&lt;/item&gt;&lt;/item&gt;&lt;/item&gt;&lt;/item&gt;&lt;/code&gt;
&lt;/pre&gt;

&lt;div&gt;&lt;p data-sourcepos=&quot;3:1-3:18&quot; style=&quot;background-color: white; color: #1f1f1f; font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px; margin: 24px 0px; white-space-collapse: preserve; word-break: break-word;&quot;&gt;&lt;br /&gt;&lt;/p&gt;&lt;h2 style=&quot;background-color: white; color: #1f1f1f; font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px; margin: 24px 0px; text-align: left; white-space-collapse: preserve; word-break: break-word;&quot;&gt;Explanation of code&lt;/h2&gt;&lt;p data-sourcepos=&quot;3:1-3:18&quot; style=&quot;background-color: white; color: #1f1f1f; font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px; margin: 24px 0px; white-space-collapse: preserve; word-break: break-word;&quot;&gt;1. Item Class:&lt;/p&gt;&lt;span face=&quot;&amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif&quot; style=&quot;background-color: white; color: #1f1f1f; font-size: 16px;&quot;&gt;&lt;/span&gt;&lt;ul data-sourcepos=&quot;4:4-4:50&quot; style=&quot;background-color: white; color: #1f1f1f; font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px; margin: 4px 0px; padding-inline-start: 36px;&quot;&gt;&lt;li data-sourcepos=&quot;4:4-4:50&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Represents an item with its value and weight.&lt;/li&gt;&lt;/ul&gt;&lt;span face=&quot;&amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif&quot; style=&quot;background-color: white; color: #1f1f1f; font-size: 16px;&quot;&gt;&lt;/span&gt;&lt;p data-sourcepos=&quot;6:1-6:25&quot; style=&quot;background-color: white; color: #1f1f1f; font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px; margin: 24px 0px; white-space-collapse: preserve; word-break: break-word;&quot;&gt;2. knapsack() Method:&lt;/p&gt;&lt;span face=&quot;&amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif&quot; style=&quot;background-color: white; color: #1f1f1f; font-size: 16px;&quot;&gt;&lt;/span&gt;&lt;ul data-sourcepos=&quot;7:4-8:9&quot; style=&quot;background-color: white; color: #1f1f1f; font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px; margin: 4px 0px; padding-inline-start: 36px;&quot;&gt;&lt;li data-sourcepos=&quot;7:4-7:60&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Takes a list of items and a knapsack capacity as input.&lt;/li&gt;&lt;li data-sourcepos=&quot;8:4-8:9&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Uses dynamic programming to solve the 0-1 Knapsack Problem.&lt;/li&gt;&lt;li data-sourcepos=&quot;9:4-9:99&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Returns a list of selected items that maximize the total value without exceeding the capacity.&lt;/li&gt;&lt;/ul&gt;&lt;span face=&quot;&amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif&quot; style=&quot;background-color: white; color: #1f1f1f; font-size: 16px;&quot;&gt;&lt;/span&gt;&lt;h4 style=&quot;background-color: white; color: #1f1f1f; font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px; margin: 24px 0px; text-align: left; white-space-collapse: preserve; word-break: break-word;&quot;&gt;Steps&lt;/h4&gt;&lt;span face=&quot;&amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif&quot; style=&quot;background-color: white; color: #1f1f1f; font-size: 16px;&quot;&gt;&lt;/span&gt;&lt;ul data-sourcepos=&quot;13:4-14:7&quot; style=&quot;background-color: white; color: #1f1f1f; font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px; margin: 4px 0px; padding-inline-start: 36px;&quot;&gt;&lt;li data-sourcepos=&quot;13:4-13:75&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Create a 2D DP array:&amp;nbsp;Stores intermediate results for subproblems.&lt;/li&gt;&lt;li data-sourcepos=&quot;14:4-14:7&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Fill the DP array:&lt;ul data-sourcepos=&quot;15:7-16:114&quot; style=&quot;margin: 4px 0px; padding-inline-start: 36px;&quot;&gt;&lt;li data-sourcepos=&quot;15:7-15:45&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Iterate through items and capacities.&lt;/li&gt;&lt;li data-sourcepos=&quot;16:7-16:114&quot; style=&quot;margin-bottom: 10px;&quot;&gt;For each cell,&amp;nbsp;calculate the maximum value achievable considering the current item and remaining capacity.&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;li data-sourcepos=&quot;17:4-18:0&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Reconstruct the solution:&amp;nbsp;Backtrack through the DP array to find the selected items.&lt;/li&gt;&lt;/ul&gt;&lt;span face=&quot;&amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif&quot; style=&quot;background-color: white; color: #1f1f1f; font-size: 16px;&quot;&gt;&lt;/span&gt;&lt;h4 style=&quot;background-color: white; color: #1f1f1f; font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px; margin: 24px 0px; text-align: left; white-space-collapse: preserve; word-break: break-word;&quot;&gt;Take away points&lt;/h4&gt;&lt;span face=&quot;&amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif&quot; style=&quot;background-color: white; color: #1f1f1f; font-size: 16px;&quot;&gt;&lt;/span&gt;&lt;ul data-sourcepos=&quot;21:4-23:69&quot; style=&quot;background-color: white; color: #1f1f1f; font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px; margin: 4px 0px; padding-inline-start: 36px;&quot;&gt;&lt;li data-sourcepos=&quot;21:4-21:96&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Bottom-up approach:&amp;nbsp;Builds the solution from smaller subproblems to the final solution.&lt;/li&gt;&lt;li data-sourcepos=&quot;22:4-22:102&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Dynamic programming principle:&amp;nbsp;Avoids redundant calculations by storing intermediate results.&lt;/li&gt;&lt;li data-sourcepos=&quot;23:4-23:69&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Time complexity:&amp;nbsp;O(nW),&amp;nbsp;where n is the number of items and W is the capacity.&lt;/li&gt;&lt;li data-sourcepos=&quot;24:4-25:0&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Space complexity:&amp;nbsp;O(nW),&amp;nbsp;due to the DP array.&lt;/li&gt;&lt;/ul&gt;&lt;span face=&quot;&amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif&quot; style=&quot;background-color: white; color: #1f1f1f; font-size: 16px;&quot;&gt;&lt;/span&gt;&lt;/div&gt;</description><link>http://simplestcodings.blogspot.com/2023/12/knapsack-problem.html</link><author>noreply@blogger.com (Varun)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi42EONRKkCLItUT8CdBXjHnDCDOUxH2ZZXRoFEc_-gqObYrPkCZeqpwA3ANztIzWxfwHhrs3gX4uY0ktkuDfntqyOCWQ-i_gCriHbmk0TApMSGUuyuFg6YJv9lC4hZDwnUTVu2Y5rPR_MlkKScdkuTO0dK8LsMdxiBWsBrs1Xv3ibl-OXrUtzqmOmJi_s/s72-w686-h232-c/Weights.png" height="72" width="72"/><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-3459284654925679524.post-8522537935253249454</guid><pubDate>Wed, 20 Dec 2023 14:40:00 +0000</pubDate><atom:updated>2023-12-20T22:49:07.950+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">Dijkstra</category><category domain="http://www.blogger.com/atom/ns#">Dijkstra Java implementation</category><category domain="http://www.blogger.com/atom/ns#">Graphs</category><category domain="http://www.blogger.com/atom/ns#">Java</category><category domain="http://www.blogger.com/atom/ns#">Shortest Path Algorithm</category><title>Dijkstra algorithm implementation in Java</title><description>&lt;div&gt;&lt;h3 style=&quot;background-color: white; color: #1f1f1f; font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px; margin: 24px 0px; text-align: left; white-space-collapse: preserve; word-break: break-word;&quot;&gt;&lt;div&gt;&lt;span data-canva-clipboard=&quot;ewAiAGEAIgA6ADUALAAiAGQAIgA6ACIAQgAiACwAIgBoACIAOgAiAHcAdwB3AC4AYwBhAG4AdgBhAC4AYwBvAG0AIgAsACIAYwAiADoAIgBEAEEARgAzAGkAQQBjAFYATAB0AEEAIgAsACIAaQAiADoAIgBHAF8ASQBIADYARgAtADYAegBMADQAWQAwAE4AcwBfAEMAWgA0AGEAbQBRACIALAAiAGIAIgA6ADEANwAwADMAMAA5ADIAMwA1ADUAMQAzADEALAAiAGoAIgA6AFsAewAiAEEAIgA6AHsAIgBCACIAOgB7AH0ALAAiAEsAIgA6AHsAfQAsACIARAAiADoAewB9ACwAIgBMACIAOgB7ACIAQQAiADoAWwB7ACIAQQAiADoAewB9ACwAIgBCACIAOgAiAEMAIgB9ACwAewAiAEEAIgA6AHsAfQAsACIAQgAiADoAIgBCACIAfQBdAH0ALAAiAEUAIgA6AHsAfQAsACIARgAiADoAewAiAEEAIgA6ACIASQBkAGUAbgB0AGkAdAB5AC4AcABuAGcAIgAsACIAQgAiADoAMQB9ACwAIgBHACIAOgB7AH0ALAAiAEgAIgA6AHsAIgBCACIAOgAiAG4AbwBuAGUAIgAsACIAQwAiADoAIgAjADAAMAAwADAAMAAwACIALAAiAEQAIgA6ACIAIwBmAGYAZgBmAGYAZgAiAH0ALAAiAEoAIgA6AHsAIgBGACIAOgAiACMAMAAwADAAMAAwADAAIgB9ACwAIgBQACIAOgB7AH0AfQB9AF0ALAAiAEEAPwAiADoAIgBCACIALAAiAEEAIgA6AFsAewAiAEEAIgA6ADYANAAsACIAQgAiADoALQA0ADgAMAAsACIARAAiADoANAA3ADkALgA5ADkAOQA5ADkAOQA5ADkAOQA5ADkAOQA5ACwAIgBDACIAOgA0ADcAOQAuADkAOQA5ADkAOQA5ADkAOQA5ADkAOQA5ADkALAAiAEEAPwAiADoAIgBJACIALAAiAGEAIgA6AHsAIgBCACIAOgB7ACIAQQAiADoAewAiAEEAIgA6ACIATQBBAEYAMwBpAGQAeAB1AEEAWgA0ACIALAAiAEIAIgA6ADEAfQAsACIAQgAiADoAewAiAEEAIgA6ADIALgA4ADQAMgAxADcAMAA5ADQAMwAwADQAMAA0ADAAMQBlAC0AMQA0ACwAIgBCACIAOgAyAC4AOAA0ADIAMQA3ADAAOQA0ADMAMAA0ADAANAAwADEAZQAtADEANAAsACIARAAiADoANAA3ADkALgA5ADkAOQA5ADkAOQA5ADkAOQA5ADkAOQA5ACwAIgBDACIAOgA0ADcAOQAuADkAOQA5ADkAOQA5ADkAOQA5ADkAOQA5ADkAfQB9AH0AfQBdACwAIgBCACIAOgAtADEALAAiAEMAIgA6AC0AMQB9AA==&quot;&gt;&lt;/span&gt;&lt;/div&gt;&lt;br /&gt;&lt;/h3&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgwIUvtfuSz-DIBItAcHeTUNTsuDzr-DpfSTkeAnvRLXwNWDZnDEOsx4RZUOpqY0MJjAcpWbQAvxjKz9Zl7joUHFjE9KRVXxEQxoAdDEYD2UbYl2bVweYDeMi1rQ3nvHzuQAFIBPe-x2yoKYPDPzipphYH4tFOmL5C6Q3XibrE4fNyj5LpXcmJAuPpWyUg/s896/shortestroute.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;448&quot; data-original-width=&quot;896&quot; height=&quot;320&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgwIUvtfuSz-DIBItAcHeTUNTsuDzr-DpfSTkeAnvRLXwNWDZnDEOsx4RZUOpqY0MJjAcpWbQAvxjKz9Zl7joUHFjE9KRVXxEQxoAdDEYD2UbYl2bVweYDeMi1rQ3nvHzuQAFIBPe-x2yoKYPDPzipphYH4tFOmL5C6Q3XibrE4fNyj5LpXcmJAuPpWyUg/w639-h320/shortestroute.png&quot; width=&quot;639&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;h3 style=&quot;background-color: white; color: #1f1f1f; font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px; margin: 24px 0px; text-align: left; white-space-collapse: preserve; word-break: break-word;&quot;&gt;Purpose&lt;/h3&gt;&lt;span face=&quot;&amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif&quot; style=&quot;background-color: white; color: #1f1f1f; font-size: 16px;&quot;&gt;&lt;/span&gt;&lt;ul data-sourcepos=&quot;5:1-5:67&quot; style=&quot;background-color: white; color: #1f1f1f; font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px; margin: 4px 0px; padding-inline-start: 36px;&quot;&gt;&lt;li data-sourcepos=&quot;5:1-5:67&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Finds the shortest paths from a single source vertex to all other vertices in a weighted graph.&lt;/li&gt;&lt;li data-sourcepos=&quot;6:1-7:0&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Commonly used in GPS navigation,&amp;nbsp;network routing,&amp;nbsp;and logistics planning.&lt;/li&gt;&lt;/ul&gt;&lt;span face=&quot;&amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif&quot; style=&quot;background-color: white; color: #1f1f1f; font-size: 16px;&quot;&gt;&lt;/span&gt;&lt;h3 style=&quot;background-color: white; color: #1f1f1f; font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px; margin: 24px 0px; text-align: left; white-space-collapse: preserve; word-break: break-word;&quot;&gt;Key Concepts&lt;/h3&gt;&lt;span face=&quot;&amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif&quot; style=&quot;background-color: white; color: #1f1f1f; font-size: 16px;&quot;&gt;&lt;/span&gt;&lt;ul data-sourcepos=&quot;10:1-10:1&quot; style=&quot;background-color: white; color: #1f1f1f; font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px; margin: 4px 0px; padding-inline-start: 36px;&quot;&gt;&lt;li data-sourcepos=&quot;10:1-10:1&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Weighted Graph:&amp;nbsp;A set of vertices (nodes) connected by edges with associated weights (distances,&amp;nbsp;costs,&amp;nbsp;etc.).&lt;/li&gt;&lt;li data-sourcepos=&quot;11:1-11:20&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Source Vertex:&amp;nbsp;The starting point for finding shortest paths.&lt;/li&gt;&lt;li data-sourcepos=&quot;12:1-13:0&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Shortest Path:&amp;nbsp;The path with the minimum total weight between two vertices.&lt;/li&gt;&lt;/ul&gt;&lt;span face=&quot;&amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif&quot; style=&quot;background-color: white; color: #1f1f1f; font-size: 16px;&quot;&gt;&lt;/span&gt;&lt;h3 style=&quot;background-color: white; color: #1f1f1f; font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px; margin: 24px 0px; text-align: left; white-space-collapse: preserve; word-break: break-word;&quot;&gt;Algorithm Steps&lt;/h3&gt;&lt;span face=&quot;&amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif&quot; style=&quot;background-color: white; color: #1f1f1f; font-size: 16px;&quot;&gt;&lt;/span&gt;&lt;ol data-sourcepos=&quot;16:1-24:65&quot; style=&quot;background-color: white; color: #1f1f1f; font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px; margin: 4px 0px; padding-inline-start: 36px;&quot;&gt;&lt;li data-sourcepos=&quot;16:1-21:0&quot; style=&quot;margin-bottom: 10px;&quot;&gt;&lt;p data-sourcepos=&quot;16:4-16:22&quot; style=&quot;margin: 24px 0px; white-space-collapse: preserve; word-break: break-word;&quot;&gt;Initialization:&lt;/p&gt;&lt;ul data-sourcepos=&quot;17:4-21:0&quot; style=&quot;margin: 4px 0px; padding-inline-start: 36px;&quot;&gt;&lt;li data-sourcepos=&quot;17:4-17:66&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Create a set&amp;nbsp;&lt;code style=&quot;background-color: var(--bard-color-surface-container-high); border-radius: 6px; color: var(--bard-color-on-surface-variant); font-family: &amp;quot;Google Sans Mono&amp;quot;, monospace; font-size: 0.875rem; line-height: 1.25rem; padding: 1px 6px;&quot;&gt;S&lt;/code&gt;&amp;nbsp;to store visited vertices (initially empty).&lt;/li&gt;&lt;li data-sourcepos=&quot;18:4-18:112&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Initialize an array&amp;nbsp;&lt;code style=&quot;background-color: var(--bard-color-surface-container-high); border-radius: 6px; color: var(--bard-color-on-surface-variant); font-family: &amp;quot;Google Sans Mono&amp;quot;, monospace; font-size: 0.875rem; line-height: 1.25rem; padding: 1px 6px;&quot;&gt;distances&lt;/code&gt;&amp;nbsp;with infinite values for all vertices except the source,&amp;nbsp;which is set to 0.&lt;/li&gt;&lt;li data-sourcepos=&quot;19:4-19:93&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Create a priority queue&amp;nbsp;&lt;code style=&quot;background-color: var(--bard-color-surface-container-high); border-radius: 6px; color: var(--bard-color-on-surface-variant); font-family: &amp;quot;Google Sans Mono&amp;quot;, monospace; font-size: 0.875rem; line-height: 1.25rem; padding: 1px 6px;&quot;&gt;Q&lt;/code&gt;&amp;nbsp;to store vertices,&amp;nbsp;prioritized by their tentative distances.&lt;/li&gt;&lt;li data-sourcepos=&quot;20:4-21:0&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Add the source vertex to&amp;nbsp;&lt;code style=&quot;background-color: var(--bard-color-surface-container-high); border-radius: 6px; color: var(--bard-color-on-surface-variant); font-family: &amp;quot;Google Sans Mono&amp;quot;, monospace; font-size: 0.875rem; line-height: 1.25rem; padding: 1px 6px;&quot;&gt;Q&lt;/code&gt;.&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;li data-sourcepos=&quot;22:1-24:65&quot; style=&quot;margin-bottom: 10px;&quot;&gt;&lt;p data-sourcepos=&quot;22:4-22:24&quot; style=&quot;margin: 24px 0px; white-space-collapse: preserve; word-break: break-word;&quot;&gt;Exploration Loop:&lt;/p&gt;&lt;ul data-sourcepos=&quot;23:4-24:65&quot; style=&quot;margin: 4px 0px; padding-inline-start: 36px;&quot;&gt;&lt;li data-sourcepos=&quot;23:4-24:65&quot; style=&quot;margin-bottom: 10px;&quot;&gt;While&amp;nbsp;&lt;code style=&quot;background-color: var(--bard-color-surface-container-high); border-radius: 6px; color: var(--bard-color-on-surface-variant); font-family: &amp;quot;Google Sans Mono&amp;quot;, monospace; font-size: 0.875rem; line-height: 1.25rem; padding: 1px 6px;&quot;&gt;Q&lt;/code&gt;&amp;nbsp;is not empty:&lt;ul data-sourcepos=&quot;24:6-24:65&quot; style=&quot;margin: 4px 0px; padding-inline-start: 36px;&quot;&gt;&lt;li data-sourcepos=&quot;24:6-24:65&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Extract the vertex&amp;nbsp;&lt;code style=&quot;background-color: var(--bard-color-surface-container-high); border-radius: 6px; color: var(--bard-color-on-surface-variant); font-family: &amp;quot;Google Sans Mono&amp;quot;, monospace; font-size: 0.875rem; line-height: 1.25rem; padding: 1px 6px;&quot;&gt;u&lt;/code&gt;&amp;nbsp;with the minimum distance from&amp;nbsp;&lt;code style=&quot;background-color: var(--bard-color-surface-container-high); border-radius: 6px; color: var(--bard-color-on-surface-variant); font-family: &amp;quot;Google Sans Mono&amp;quot;, monospace; font-size: 0.875rem; line-height: 1.25rem; padding: 1px 6px;&quot;&gt;Q&lt;/code&gt;.&lt;/li&gt;&lt;li data-sourcepos=&quot;25:6-25:48&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Add&amp;nbsp;&lt;code style=&quot;background-color: var(--bard-color-surface-container-high); border-radius: 6px; color: var(--bard-color-on-surface-variant); font-family: &amp;quot;Google Sans Mono&amp;quot;, monospace; font-size: 0.875rem; line-height: 1.25rem; padding: 1px 6px;&quot;&gt;u&lt;/code&gt;&amp;nbsp;to the set&amp;nbsp;&lt;code style=&quot;background-color: var(--bard-color-surface-container-high); border-radius: 6px; color: var(--bard-color-on-surface-variant); font-family: &amp;quot;Google Sans Mono&amp;quot;, monospace; font-size: 0.875rem; line-height: 1.25rem; padding: 1px 6px;&quot;&gt;S&lt;/code&gt;&amp;nbsp;(mark as visited).&lt;/li&gt;&lt;li data-sourcepos=&quot;26:6-30:0&quot; style=&quot;margin-bottom: 10px;&quot;&gt;For each neighbor vertex&amp;nbsp;&lt;code style=&quot;background-color: var(--bard-color-surface-container-high); border-radius: 6px; color: var(--bard-color-on-surface-variant); font-family: &amp;quot;Google Sans Mono&amp;quot;, monospace; font-size: 0.875rem; line-height: 1.25rem; padding: 1px 6px;&quot;&gt;v&lt;/code&gt;&amp;nbsp;of&amp;nbsp;&lt;code style=&quot;background-color: var(--bard-color-surface-container-high); border-radius: 6px; color: var(--bard-color-on-surface-variant); font-family: &amp;quot;Google Sans Mono&amp;quot;, monospace; font-size: 0.875rem; line-height: 1.25rem; padding: 1px 6px;&quot;&gt;u&lt;/code&gt;:&lt;ul data-sourcepos=&quot;27:8-30:0&quot; style=&quot;margin: 4px 0px; padding-inline-start: 36px;&quot;&gt;&lt;li data-sourcepos=&quot;27:8-30:0&quot; style=&quot;margin-bottom: 10px;&quot;&gt;If&amp;nbsp;&lt;code style=&quot;background-color: var(--bard-color-surface-container-high); border-radius: 6px; color: var(--bard-color-on-surface-variant); font-family: &amp;quot;Google Sans Mono&amp;quot;, monospace; font-size: 0.875rem; line-height: 1.25rem; padding: 1px 6px;&quot;&gt;v&lt;/code&gt;&amp;nbsp;is not visited and the distance to&amp;nbsp;&lt;code style=&quot;background-color: var(--bard-color-surface-container-high); border-radius: 6px; color: var(--bard-color-on-surface-variant); font-family: &amp;quot;Google Sans Mono&amp;quot;, monospace; font-size: 0.875rem; line-height: 1.25rem; padding: 1px 6px;&quot;&gt;v&lt;/code&gt;&amp;nbsp;through&amp;nbsp;&lt;code style=&quot;background-color: var(--bard-color-surface-container-high); border-radius: 6px; color: var(--bard-color-on-surface-variant); font-family: &amp;quot;Google Sans Mono&amp;quot;, monospace; font-size: 0.875rem; line-height: 1.25rem; padding: 1px 6px;&quot;&gt;u&lt;/code&gt;&amp;nbsp;is shorter than its current distance:&lt;ul data-sourcepos=&quot;28:10-30:0&quot; style=&quot;margin: 4px 0px; padding-inline-start: 36px;&quot;&gt;&lt;li data-sourcepos=&quot;28:10-28:63&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Update the distance to&amp;nbsp;&lt;code style=&quot;background-color: var(--bard-color-surface-container-high); border-radius: 6px; color: var(--bard-color-on-surface-variant); font-family: &amp;quot;Google Sans Mono&amp;quot;, monospace; font-size: 0.875rem; line-height: 1.25rem; padding: 1px 6px;&quot;&gt;v&lt;/code&gt;&amp;nbsp;in the&amp;nbsp;&lt;code style=&quot;background-color: var(--bard-color-surface-container-high); border-radius: 6px; color: var(--bard-color-on-surface-variant); font-family: &amp;quot;Google Sans Mono&amp;quot;, monospace; font-size: 0.875rem; line-height: 1.25rem; padding: 1px 6px;&quot;&gt;distances&lt;/code&gt;&amp;nbsp;array.&lt;/li&gt;&lt;li data-sourcepos=&quot;29:10-30:0&quot; style=&quot;margin-bottom: 10px;&quot;&gt;Add&amp;nbsp;&lt;code style=&quot;background-color: var(--bard-color-surface-container-high); border-radius: 6px; color: var(--bard-color-on-surface-variant); font-family: &amp;quot;Google Sans Mono&amp;quot;, monospace; font-size: 0.875rem; line-height: 1.25rem; padding: 1px 6px;&quot;&gt;v&lt;/code&gt;&amp;nbsp;to the priority queue&amp;nbsp;&lt;code style=&quot;background-color: var(--bard-color-surface-container-high); border-radius: 6px; color: var(--bard-color-on-surface-variant); font-family: &amp;quot;Google Sans Mono&amp;quot;, monospace; font-size: 0.875rem; line-height: 1.25rem; padding: 1px 6px;&quot;&gt;Q&lt;/code&gt;&amp;nbsp;(or update its priority if already present).&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;li data-sourcepos=&quot;31:1-34:0&quot; style=&quot;margin-bottom: 10px;&quot;&gt;&lt;p data-sourcepos=&quot;31:4-31:14&quot; style=&quot;margin: 24px 0px; white-space-collapse: preserve; word-break: break-word;&quot;&gt;Result:&lt;/p&gt;&lt;ul data-sourcepos=&quot;32:4-34:0&quot; style=&quot;margin: 4px 0px; padding-inline-start: 36px;&quot;&gt;&lt;li data-sourcepos=&quot;32:4-32:108&quot; style=&quot;margin-bottom: 10px;&quot;&gt;The&amp;nbsp;&lt;code style=&quot;background-color: var(--bard-color-surface-container-high); border-radius: 6px; color: var(--bard-color-on-surface-variant); font-family: &amp;quot;Google Sans Mono&amp;quot;, monospace; font-size: 0.875rem; line-height: 1.25rem; padding: 1px 6px;&quot;&gt;distances&lt;/code&gt;&amp;nbsp;array now contains the shortest distances from the source vertex to all other vertices.&lt;/li&gt;&lt;li data-sourcepos=&quot;33:4-34:0&quot; style=&quot;margin-bottom: 10px;&quot;&gt;To reconstruct the actual shortest paths,&amp;nbsp;keep track of the predecessor of each vertex during the exploration.&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;/ol&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;&lt;code class=&quot;language-java&quot;&gt;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Random;
import java.util.stream.Collectors;

public class Dijkstra {

    public static List&lt;integer&gt; dijkstra(Graph graph, int source) {
        int[] distances = new int[graph.numVertices];
        Arrays.fill(distances, Integer.MAX_VALUE);
        distances[source] = 0;
        PriorityQueue&lt;integer&gt; pq = new PriorityQueue&amp;lt;&amp;gt;(Comparator.comparingInt(i -&amp;gt; distances[i]));
        pq.offer(source);

        boolean[] visited = new boolean[graph.numVertices];
        while (!pq.isEmpty()) {
            int u = pq.poll();
            visited[u] = true;
            for (Edge edge : graph.adjacencyList.get(u)) {
                int v = edge.to;
                int weight = edge.weight;
                if (!visited[v] &amp;amp;&amp;amp; distances[u] + weight &amp;lt; distances[v]) {
                    distances[v] = distances[u] + weight;
                    pq.offer(v);
                }
            }
        }

        return Arrays.stream(distances).boxed().collect(Collectors.toList());
    }

    public static Graph createRandomGraph(int numVertices) {
        Graph graph = new Graph(numVertices);
        Random random = new Random();
        // Add edges with random weights
        for (int i = 0; i &amp;lt; 9; i++) {
            for (int j = i + 1; j &amp;lt; 9; j++) {
                // Decide whether to create an edge with 50% probability
                if (random.nextBoolean()) {
                    int weight = random.nextInt(10) + 1; // Random weight between 1 and 10
                    graph.addEdge(i, j, weight);
                    graph.addEdge(j, i, weight); // Add reverse edge for undirected graph (if needed)
                }
            }
        }
        return graph;
    }

    public static void main(String[] args) {
        // Create a sample graph
        Graph graph = createRandomGraph(9);
        graph.visualize();
        int source = 0;
        List&lt;integer&gt; distances = dijkstra(graph, source);
        System.out.println(&quot;Shortest distances from &quot; + source + &quot;: &quot; + distances);
    }

    public static class Edge {
        int to;
        int weight;

        Edge(int to, int weight) {
            this.to = to;
            this.weight = weight;
        }
    }

    public static class Graph {
        int numVertices;
        List&lt;list dge=&quot;&quot;&gt;&amp;gt; adjacencyList;

        Graph(int numVertices) {
            this.numVertices = numVertices;
            adjacencyList = new ArrayList&amp;lt;&amp;gt;();
            for (int i = 0; i &amp;lt; numVertices; i++) {
                adjacencyList.add(new ArrayList&amp;lt;&amp;gt;());
            }
        }

        void addEdge(int from, int to, int weight) {
            adjacencyList.get(from).add(new Edge(to, weight));
        }

        void visualize() {
            System.out.println(&quot;Graph Visualization:\n&quot;);
            for (int vertex = 0; vertex &amp;lt; numVertices; vertex++) {
                System.out.print(vertex + &quot; -&amp;gt; &quot;);
                for (Edge edge : adjacencyList.get(vertex)) {
                    System.out.print(edge.to + &quot;(&quot; + edge.weight + &quot;) &quot;);
                }
                System.out.println();
            }
        }
    }
}

&lt;/list&gt;&lt;/integer&gt;&lt;/integer&gt;&lt;/integer&gt;&lt;/code&gt;
&lt;/pre&gt;

&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;h2 style=&quot;text-align: left;&quot;&gt;&lt;span style=&quot;font-family: inherit;&quot;&gt;
Explanation of code&lt;/span&gt;&lt;/h2&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;ul data-sourcepos=&quot;9:1-21:0&quot; style=&quot;background-color: white; color: #1f1f1f; font-family: &amp;quot;Google Sans&amp;quot;, &amp;quot;Helvetica Neue&amp;quot;, sans-serif; font-size: 16px; margin: 4px 0px; padding-inline-start: 36px; text-align: left;&quot;&gt;&lt;li data-sourcepos=&quot;9:1-12:0&quot; style=&quot;margin-bottom: 10px;&quot;&gt;&lt;h4 style=&quot;margin: 0px 0px 24px; white-space-collapse: preserve; word-break: break-word;&quot;&gt;Graph Representation&lt;/h4&gt;&lt;ul data-sourcepos=&quot;10:5-12:0&quot; style=&quot;margin: 4px 0px; padding-inline-start: 36px;&quot;&gt;&lt;li data-sourcepos=&quot;10:5-10:137&quot; style=&quot;margin-bottom: 10px;&quot;&gt;The&amp;nbsp;&lt;code style=&quot;background-color: var(--bard-color-surface-container-high); border-radius: 6px; color: var(--bard-color-on-surface-variant); font-family: &amp;quot;Google Sans Mono&amp;quot;, monospace; font-size: 0.875rem; line-height: 1.25rem; padding: 1px 6px;&quot;&gt;Graph&lt;/code&gt;&amp;nbsp;class models a graph using an adjacency list, where each vertex stores a list of its connected edges and their weights.&lt;/li&gt;&lt;li data-sourcepos=&quot;11:5-12:0&quot; style=&quot;margin-bottom: 10px;&quot;&gt;The&amp;nbsp;&lt;code style=&quot;background-color: var(--bard-color-surface-container-high); border-radius: 6px; color: var(--bard-color-on-surface-variant); font-family: &amp;quot;Google Sans Mono&amp;quot;, monospace; font-size: 0.875rem; line-height: 1.25rem; padding: 1px 6px;&quot;&gt;Edge&lt;/code&gt;&amp;nbsp;class encapsulates the destination vertex and weight of an edge.&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;li data-sourcepos=&quot;13:1-18:0&quot; style=&quot;margin-bottom: 10px;&quot;&gt;&lt;h4 style=&quot;margin: 0px 0px 24px; white-space-collapse: preserve; word-break: break-word;&quot;&gt;Dijkstra&#39;s Algorithm Implementation&lt;/h4&gt;&lt;ul data-sourcepos=&quot;14:5-18:0&quot; style=&quot;margin: 4px 0px; padding-inline-start: 36px;&quot;&gt;&lt;li data-sourcepos=&quot;14:5-18:0&quot; style=&quot;margin-bottom: 10px;&quot;&gt;The&amp;nbsp;&lt;code style=&quot;background-color: var(--bard-color-surface-container-high); border-radius: 6px; color: var(--bard-color-on-surface-variant); font-family: &amp;quot;Google Sans Mono&amp;quot;, monospace; font-size: 0.875rem; line-height: 1.25rem; padding: 1px 6px;&quot;&gt;dijkstra(Graph, source)&lt;/code&gt;&amp;nbsp;method implements the algorithm&#39;s logic:&lt;ul data-sourcepos=&quot;15:7-18:0&quot; style=&quot;margin: 4px 0px; padding-inline-start: 36px;&quot;&gt;&lt;li data-sourcepos=&quot;15:7-15:96&quot; style=&quot;margin-bottom: 10px;&quot;&gt;It maintains a priority queue to explore vertices in order of their tentative distances.&lt;/li&gt;&lt;li data-sourcepos=&quot;16:7-16:88&quot; style=&quot;margin-bottom: 10px;&quot;&gt;It iteratively relaxes edges to update distances and explore reachable vertices.&lt;/li&gt;&lt;li data-sourcepos=&quot;17:7-18:0&quot; style=&quot;margin-bottom: 10px;&quot;&gt;It ultimately returns a list of the shortest distances from the source vertex to all other vertices.&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;li data-sourcepos=&quot;19:1-21:0&quot; style=&quot;margin-bottom: 10px;&quot;&gt;&lt;h4 style=&quot;margin: 0px 0px 24px; white-space-collapse: preserve; word-break: break-word;&quot;&gt;Random Graph Generation&lt;/h4&gt;&lt;ul data-sourcepos=&quot;20:5-21:0&quot; style=&quot;margin: 4px 0px; padding-inline-start: 36px;&quot;&gt;&lt;li data-sourcepos=&quot;20:5-21:0&quot; style=&quot;margin-bottom: 10px;&quot;&gt;The&amp;nbsp;&lt;code style=&quot;background-color: var(--bard-color-surface-container-high); border-radius: 6px; color: var(--bard-color-on-surface-variant); font-family: &amp;quot;Google Sans Mono&amp;quot;, monospace; font-size: 0.875rem; line-height: 1.25rem; padding: 1px 6px;&quot;&gt;createRandomGraph(numVertices)&lt;/code&gt;&amp;nbsp;method generates a graph with a specified number of vertices and randomly assigns edges with weights between 1 and 10.&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/div&gt;



</description><link>http://simplestcodings.blogspot.com/2023/12/dijkstra-algorithm-implementation-in.html</link><author>noreply@blogger.com (Varun)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgwIUvtfuSz-DIBItAcHeTUNTsuDzr-DpfSTkeAnvRLXwNWDZnDEOsx4RZUOpqY0MJjAcpWbQAvxjKz9Zl7joUHFjE9KRVXxEQxoAdDEYD2UbYl2bVweYDeMi1rQ3nvHzuQAFIBPe-x2yoKYPDPzipphYH4tFOmL5C6Q3XibrE4fNyj5LpXcmJAuPpWyUg/s72-w639-h320-c/shortestroute.png" height="72" width="72"/><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-3459284654925679524.post-5109847722655664026</guid><pubDate>Wed, 12 Oct 2016 17:11:00 +0000</pubDate><atom:updated>2023-12-20T21:23:57.715+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">auto-suggestion</category><category domain="http://www.blogger.com/atom/ns#">autocomplete</category><category domain="http://www.blogger.com/atom/ns#">C</category><category domain="http://www.blogger.com/atom/ns#">data structure</category><category domain="http://www.blogger.com/atom/ns#">dictionaries</category><category domain="http://www.blogger.com/atom/ns#">natural language processing</category><category domain="http://www.blogger.com/atom/ns#">prefix search</category><category domain="http://www.blogger.com/atom/ns#">Search Algorithm</category><category domain="http://www.blogger.com/atom/ns#">string storage</category><category domain="http://www.blogger.com/atom/ns#">Ternary Search</category><category domain="http://www.blogger.com/atom/ns#">TST deletion</category><category domain="http://www.blogger.com/atom/ns#">TST insertion</category><category domain="http://www.blogger.com/atom/ns#">TST search</category><title>Ternary Search Tree Implementation in C++</title><description>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
A Ternary Search Tree is a trie which leverages concepts of Binary Search Tree as well. A Ternary Search Tree is as memory efficient as Binary Search Trees and time efficient as a Trie.&lt;br /&gt;
&lt;br /&gt;
It is an efficient data structure to store and search large number of strings.&lt;br /&gt;
&lt;br /&gt;
A node in a Ternary Search Tree comprises of these fields :&lt;br /&gt;
&lt;br /&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;Left pointer - Points to&amp;nbsp;Ternary Search Tree containing&amp;nbsp;all strings alphabetically lesser than current node&#39;s data&lt;/li&gt;
&lt;li&gt;Right pointer - Points to&amp;nbsp;Ternary Search Tree&amp;nbsp;containing&amp;nbsp;all&amp;nbsp;strings&amp;nbsp;alphabetically&amp;nbsp;greater than current node&#39;s data&lt;/li&gt;
&lt;li&gt;Equal pointer -&amp;nbsp;Points to&amp;nbsp;Ternary Search Tree&amp;nbsp;containing&amp;nbsp;all&amp;nbsp;strings&amp;nbsp;alphabetically&amp;nbsp;equal to current node&#39;s data&lt;/li&gt;
&lt;li&gt;End of string flag - Flag indicating the end of string&lt;/li&gt;
&lt;li&gt;Data - Actual data in the form of single character&lt;/li&gt;
&lt;/ul&gt;
&lt;table align=&quot;center&quot; cellpadding=&quot;0&quot; cellspacing=&quot;0&quot; class=&quot;tr-caption-container&quot; style=&quot;margin-left: auto; margin-right: auto; text-align: center;&quot;&gt;&lt;tbody&gt;
&lt;tr&gt;&lt;td style=&quot;text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEguGduD0vChiSTnjE4_z63S7c4eq03iPdCxFtxaHHmwC99f8MD3M5QUjbF4JyqEFdYk-I7Tb9igf_70_yQgztDU26LUcZlgIn_s2dZoRXB2yJsM4V5xoYsB6-BHZSiLiDJH7arkX97D3dY/s1600/Node.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: auto; margin-right: auto;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;192&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEguGduD0vChiSTnjE4_z63S7c4eq03iPdCxFtxaHHmwC99f8MD3M5QUjbF4JyqEFdYk-I7Tb9igf_70_yQgztDU26LUcZlgIn_s2dZoRXB2yJsM4V5xoYsB6-BHZSiLiDJH7arkX97D3dY/s320/Node.png&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td class=&quot;tr-caption&quot; style=&quot;text-align: center;&quot;&gt;Ternary Search Tree Node&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
For example, consider adding these strings in the same order into a Ternary Search Tree :&lt;/div&gt;
&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;ol style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;&quot;Lead&quot;&lt;/li&gt;
&lt;li&gt;&quot;Leader&quot;&lt;/li&gt;
&lt;li&gt;&quot;Leads&quot;&lt;/li&gt;
&lt;li&gt;&quot;Late&quot;&lt;/li&gt;
&lt;li&gt;&quot;State&quot;&lt;/li&gt;
&lt;/ol&gt;
Let&#39;s build a visualization of ternary search tree out of above data :

&lt;br /&gt;
&lt;div&gt;
&lt;ol style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;&quot;Lead&quot;&lt;br /&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjnOqiMU5ms2UeCZ2s5pJc6JGlSqgH5QFE9iaGm-y9SKZW1nZIF7wisYauk4HRPosylIiSpCnZv2kJKtceXl9OuIkIOC3_pfltMaHPOrKJkMRwnUJF0b-xTPnf3rkilB1APX2Ht8CDoaGg/s1600/Lead.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjnOqiMU5ms2UeCZ2s5pJc6JGlSqgH5QFE9iaGm-y9SKZW1nZIF7wisYauk4HRPosylIiSpCnZv2kJKtceXl9OuIkIOC3_pfltMaHPOrKJkMRwnUJF0b-xTPnf3rkilB1APX2Ht8CDoaGg/s1600/Lead.png&quot; /&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&quot;Leader&quot;&lt;br /&gt;&lt;br /&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjgEGLsfdy2ZNbQr9dUWhNYmRKty7Y9avPZRUjFHsDBcYOJA2PprufKYNPrrDDfUWe2LExhtxAYE9EVpbLCeuyASXGdsSWFYvzKQERTR9eKkccHkLygqJFqNEFG0tf4CfF7OAzKJxWg7Ds/s1600/Leader.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjgEGLsfdy2ZNbQr9dUWhNYmRKty7Y9avPZRUjFHsDBcYOJA2PprufKYNPrrDDfUWe2LExhtxAYE9EVpbLCeuyASXGdsSWFYvzKQERTR9eKkccHkLygqJFqNEFG0tf4CfF7OAzKJxWg7Ds/s1600/Leader.png&quot; /&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&quot;Leads&quot;&lt;br /&gt;&lt;br /&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj4zTzZRTFrUIwxuH9ZAMbW6oRhLhtsEibgAt1onQDl_xk9cRx-q4FyQqfqmS3A9sEVpH21JznHNoigH_0-ciUgM30yIqR29Bbc07LHVqY74ip-b_duN3wsllVjWi79p9M6peSEDWQk0-Q/s1600/Leads.png&quot; imageanchor=&quot;1&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj4zTzZRTFrUIwxuH9ZAMbW6oRhLhtsEibgAt1onQDl_xk9cRx-q4FyQqfqmS3A9sEVpH21JznHNoigH_0-ciUgM30yIqR29Bbc07LHVqY74ip-b_duN3wsllVjWi79p9M6peSEDWQk0-Q/s1600/Leads.png&quot; /&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&quot;Late&quot;&lt;br /&gt;&lt;br /&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh4GYrp25waQYYicgWtbrqIGM1nFMIxUfXq_ip0Yf84v4iY5ba-wN-P4kYtL1Rti7hyZwMwTRVIAerTsIbiz66ht0TzOnHtlsCBdACWX1W56Bcw4FjTNKsdg3bBUd1AVR98AHk4zgDOtE4/s1600/Late.png&quot; imageanchor=&quot;1&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh4GYrp25waQYYicgWtbrqIGM1nFMIxUfXq_ip0Yf84v4iY5ba-wN-P4kYtL1Rti7hyZwMwTRVIAerTsIbiz66ht0TzOnHtlsCBdACWX1W56Bcw4FjTNKsdg3bBUd1AVR98AHk4zgDOtE4/s1600/Late.png&quot; /&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&quot;State&quot;&lt;br /&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiuC74zCxc3WRYNIh1QGJap0Hj7X9MTA6bCCelXx8fOF0ebtAFOyNXaYJ5RYxEx6N3KtRIHL85zTDj_ZFpsRo_BiD_eJzGpvWeZnk7vLrZSLbW6CivMKW9b7ZxFSda3so7xg9jVMPWLeqU/s1600/State.png&quot; imageanchor=&quot;1&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiuC74zCxc3WRYNIh1QGJap0Hj7X9MTA6bCCelXx8fOF0ebtAFOyNXaYJ5RYxEx6N3KtRIHL85zTDj_ZFpsRo_BiD_eJzGpvWeZnk7vLrZSLbW6CivMKW9b7ZxFSda3so7xg9jVMPWLeqU/s1600/State.png&quot; /&gt;&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;
&lt;code class=&quot;language-cpp&quot;&gt;

//TST.h
#ifndef TST_H
#define TST_H
//#define DEBUG_PROGRAM_MEMORY

//Node of a Ternary Search Tree
typedef struct TSTNode{
 char data; //Actual data stored in form of character
 bool bEOS; //flag marking end of string
 struct TSTNode* left;   //All character data less than this node
 struct TSTNode* eq;  //All character data equal to this node
 struct TSTNode* right; //All character data greater than this node
}TSTNode;

//Inserts a string in the TST
TSTNode* Insert(TSTNode* root, char* str); 

//Prints all strings in the TST
void PrintAllStringsInTST(TSTNode* root);

//Gets the length of maximum length string in TST
int MaxLenStringLen(TSTNode *root);

//Deleted the complete TST
void DeleteTST(TSTNode *root);

//Search a pattern in TST
bool SearchTST(TSTNode *root, char* pattern);

//Prints 
#ifdef DEBUG_PROGRAM_MEMORY
#include &amp;lt;map&amp;gt;

static std::map&amp;lt;TSTNode*, char&amp;gt; mem_addrs;
void CheckTSTMem();
#endif

#endif

&lt;/code&gt;
&lt;/pre&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
&lt;code class=&quot;language-cpp&quot;&gt;

//TST.cpp
#include &amp;lt;iostream&amp;gt;
#define DEBUG_PROGRAM_MEMORY

#include &quot;TST.h&quot;
#include &amp;lt;cstdlib&amp;gt;
#include &amp;lt;utility&amp;gt;

#define MAX_LEN 1024

#define MAX( a, b, c ) ((a)&amp;gt;(b) ? ((a)&amp;gt;(c) ? (a):(c)) : ( (b)&amp;gt;(c) ? (b):(c) ))


TSTNode* Insert(TSTNode* root, char* str)
{
 if(root == NULL)
 {
  root = (TSTNode*)malloc(sizeof(TSTNode));
  if(root == NULL)
  {
   std::cout&amp;lt;&amp;lt;&quot;Memory allocation failed&quot;&amp;lt;&amp;lt;std::endl;
   return NULL;
  }

  //Insert first character of string in the root node
  root-&amp;gt;data = *str;
#ifdef DEBUG_PROGRAM_MEMORY
  mem_addrs.insert(std::make_pair(root, root-&amp;gt;data));
#endif
  root-&amp;gt;bEOS = false;
  root-&amp;gt;left = root-&amp;gt;eq = root-&amp;gt;right = NULL;
 }
 
 if(*str  &amp;lt; root-&amp;gt;data)
  root-&amp;gt;left = Insert(root-&amp;gt;left, str);
 else if (*str == root-&amp;gt;data)
 {
  if(*(str + 1))
   root-&amp;gt;eq = Insert(root-&amp;gt;eq, str + 1);
  else
   root-&amp;gt;bEOS = true;
 }
 else
  root-&amp;gt;right = Insert(root-&amp;gt;right, str);
 
 return root; 
}

//Helper to print the strings in TST
static void PrintHelper(TSTNode* root, char* buffer, int depth)
{
 if (root)
 {
  // Traverse the left subtree
  PrintHelper(root-&amp;gt;left, buffer, depth);

  buffer[depth] = root-&amp;gt;data;
  //Once end of string flag is encountered, print the string
  if (root-&amp;gt;bEOS)
  {
   buffer[depth + 1] = &#39;\0&#39;;
   std::cout&amp;lt;&amp;lt; buffer &amp;lt;&amp;lt; std::endl;
  }

  // Traverse the middle subtree
  PrintHelper(root-&amp;gt;eq, buffer, depth + 1);

  // Traverse the right subtree
  PrintHelper(root-&amp;gt;right, buffer, depth);
 }
}

// Function to print TST&#39;s strings
void PrintAllStringsInTST(TSTNode* root)
{
 char buffer[MAX_LEN];
 PrintHelper(root, buffer, 0);
}

bool SearchTST(TSTNode *root, char* pattern)
{
 while (root != NULL)
 {
  if (*pattern &amp;lt; root-&amp;gt;data)
   root = root-&amp;gt;left;
  else if (*pattern == root-&amp;gt;data)
  {
   //If end of string flag is found and the pattern length is also exhausted, 
   //we can safely say that the pattern is present in the TST
   if (root-&amp;gt;bEOS &amp;amp;&amp;amp; *(pattern + 1) == &#39;\0&#39;)
    return true;
   pattern++;
   root = root-&amp;gt;eq;
  }
  else
   root = root-&amp;gt;right;
 }

 return false;
}

//Function to determine largest 
int MaxLenStringLen(TSTNode *root)
{
 if (root == NULL)
  return 0;

 int leftLen = MaxLenStringLen(root-&amp;gt;left);
 int middleLen = MaxLenStringLen(root-&amp;gt;eq) + 1;
 int rightLen = MaxLenStringLen(root-&amp;gt;right);

 return MAX( leftLen, middleLen, rightLen);
}

void DeleteTST(TSTNode *root)
{
 TSTNode *tmp = root;
 if (tmp)
 {
  DeleteTST(tmp-&amp;gt;left);
  DeleteTST(tmp-&amp;gt;eq);
  DeleteTST(tmp-&amp;gt;right);

#ifdef DEBUG_PROGRAM_MEMORY
  mem_addrs.erase(tmp);
#endif
  delete tmp;
 }
}

#ifdef DEBUG_PROGRAM_MEMORY
void CheckTSTMem()
{
 std::map&amp;lt;TSTNode*, char&amp;gt;::iterator itr = mem_addrs.begin();

 if (mem_addrs.size() == 0)
 {
  std::cout &amp;lt;&amp;lt; &quot;No memory leaks&quot;;
  return;
 }

 while (itr != mem_addrs.end()) 
 {
  std::cout &amp;lt;&amp;lt; &quot;Memory address &quot; &amp;lt;&amp;lt; itr-&amp;gt;first&amp;lt;&amp;lt; &quot; for \&quot;&quot; &amp;lt;&amp;lt; itr-&amp;gt;second &amp;lt;&amp;lt; &quot;\&quot; has not been deallocated&quot; &amp;lt;&amp;lt; std::endl;
  ++itr;
 }
}
#endif

&lt;/code&gt;
&lt;/pre&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;
&lt;code class=&quot;language-cpp&quot;&gt;

//Main.cpp
#include &amp;lt;iostream&amp;gt;
#include &quot;TST.h&quot;

int main(int argc, char** argv) {
 
 TSTNode *root = NULL;
 root = Insert(root, &quot;boats&quot;);
 root = Insert(root, &quot;boat&quot;);
 root = Insert(root, &quot;bat&quot;);
 root = Insert(root, &quot;bats&quot;);
 root = Insert(root, &quot;stages&quot;);

 PrintAllStringsInTST(root);
 std::cout &amp;lt;&amp;lt; &quot;Maximum length string in this TST is of size &quot;&amp;lt;&amp;lt; MaxLenStringLen(root) &amp;lt;&amp;lt; std::endl;

 char *str = &quot;hello&quot;;
 char *str1 = &quot;bat&quot;;

 if (SearchTST(root, str) == false)
  std::cout &amp;lt;&amp;lt; &quot;\&quot;&quot;&amp;lt;&amp;lt;str&amp;lt;&amp;lt;&quot;\&quot; not found in TST&quot; &amp;lt;&amp;lt; std::endl;
 else
  std::cout &amp;lt;&amp;lt; &quot;\&quot;&quot; &amp;lt;&amp;lt; str &amp;lt;&amp;lt; &quot;\&quot; is present in TST&quot; &amp;lt;&amp;lt; std::endl;

 if (SearchTST(root, str1) == false)
  std::cout &amp;lt;&amp;lt; &quot;\&quot;&quot; &amp;lt;&amp;lt; str &amp;lt;&amp;lt; &quot;\&quot; not found in TST&quot; &amp;lt;&amp;lt; std::endl;
 else
  std::cout &amp;lt;&amp;lt; &quot;\&quot;&quot; &amp;lt;&amp;lt; str1 &amp;lt;&amp;lt; &quot;\&quot; is present in TST&quot; &amp;lt;&amp;lt; std::endl;

 DeleteTST(root);

#ifdef DEBUG_PROGRAM_MEMORY
 CheckTSTMem();
#endif
 
 return 0;
}

&lt;/code&gt;
&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
</description><link>http://simplestcodings.blogspot.com/2016/10/ternary-search-tree-implementation-in-c.html</link><author>noreply@blogger.com (Varun)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEguGduD0vChiSTnjE4_z63S7c4eq03iPdCxFtxaHHmwC99f8MD3M5QUjbF4JyqEFdYk-I7Tb9igf_70_yQgztDU26LUcZlgIn_s2dZoRXB2yJsM4V5xoYsB6-BHZSiLiDJH7arkX97D3dY/s72-c/Node.png" height="72" width="72"/><thr:total>5</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-3459284654925679524.post-7367041462673140787</guid><pubDate>Sat, 24 Sep 2016 15:01:00 +0000</pubDate><atom:updated>2023-12-20T23:02:41.178+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">efficient string matching</category><category domain="http://www.blogger.com/atom/ns#">KMP Algorithm</category><category domain="http://www.blogger.com/atom/ns#">knuth-morris-pratt algorithm</category><category domain="http://www.blogger.com/atom/ns#">pattern preprocessing</category><category domain="http://www.blogger.com/atom/ns#">prefix function</category><category domain="http://www.blogger.com/atom/ns#">Search Algorithm</category><category domain="http://www.blogger.com/atom/ns#">space complexity</category><category domain="http://www.blogger.com/atom/ns#">time complexity</category><title>String matching using KMP algorithm : C++ Implementation</title><description>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
KMP Algorithm is one the well-known string matching algorithms. It finds a pattern in a string. The pattern can exist multiple times in the string. This implementation in C++ gives indexes of all such matches in the string to be searched.&lt;br /&gt;&lt;br /&gt;
&lt;div style=&quot;text-align: left;&quot;&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhIwpmFSXZ6fIPZNZRO_GMMSp0twPbWaElt80nRNVFZxdzK_OC9JvFqWlraiHqzCg2nwli5n5BzlJF0vUM9hI0IO1lwucGc4FuoqjQyQvWFPT_XikUBqorSYA9tZc18cryOP-0E4Gir2kXjupPpTfP-zbaca6KPfq97w4lVWiTPpTVIaEJVILk_ElQz0Wo/s896/kmp.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;448&quot; data-original-width=&quot;896&quot; height=&quot;213&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhIwpmFSXZ6fIPZNZRO_GMMSp0twPbWaElt80nRNVFZxdzK_OC9JvFqWlraiHqzCg2nwli5n5BzlJF0vUM9hI0IO1lwucGc4FuoqjQyQvWFPT_XikUBqorSYA9tZc18cryOP-0E4Gir2kXjupPpTfP-zbaca6KPfq97w4lVWiTPpTVIaEJVILk_ElQz0Wo/w425-h213/kmp.png&quot; width=&quot;425&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;
e.g.&amp;nbsp;&lt;/div&gt;&lt;br /&gt;
&lt;div style=&quot;text-align: left;&quot;&gt;
String to be searched : &quot;ABCDBCAAB ABCDABCDABDE ABCDABD&quot;&lt;br /&gt;
Pattern : &quot;ABCD&quot;&lt;br /&gt;
&lt;br /&gt;
The result will be 4 index locations 0, 10, 14 and 23&lt;br /&gt;
&lt;br /&gt;
&amp;nbsp;However, there is a limitation of KMP algorithm where the pattern overlaps.&lt;br /&gt;
&lt;br /&gt;
&amp;nbsp;Consider this scenario :&lt;br /&gt;
&lt;br /&gt;
&amp;nbsp;String to be searched: &quot;ABCABCABCA&quot;&lt;br /&gt;
&amp;nbsp;Pattern: &quot;ABCA&quot;&lt;br /&gt;
&amp;nbsp;The result from KMP algorithm will be 0 and 6 locations. It cannot identify the overlapping matches &amp;nbsp;like this:&lt;br /&gt;
&amp;nbsp;&lt;b&gt;ABCA&lt;/b&gt;BCABCA&lt;br /&gt;
&amp;nbsp;ABC&lt;b&gt;ABCA&lt;/b&gt;BCA&lt;br /&gt;
&amp;nbsp;ABCABC&lt;b&gt;ABCA&lt;/b&gt;&lt;/div&gt;
&lt;div style=&quot;text-align: left;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div style=&quot;text-align: left;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;&lt;code class=&quot;language-cpp&quot;&gt;

#include &amp;lt;iostream&amp;gt;
#include &amp;lt;cstdlib&amp;gt;

using namespace std;
#define MAX_MATCHES 100

//Array to store matched indexes
int FOUND[MAX_MATCHES];
//variable to store last index in FOUND array
static int l = 0;

//Partial match table
void kmp_table(string W, int *T )
{
 int pos = 2;
 int cnd = 0;
 int length = W.length();
 
 T[0] = -1;
 T[1] = 0;
 
 while( pos &amp;lt; length)
 {
  if(W[pos-1] == W[cnd])
  {
   T[pos] = cnd + 1;
   cnd++;
   pos++;
  }
  else if( cnd &amp;gt; 0)
   cnd = T[cnd];
  else
  {
   T[pos] = 0;
   pos++;
  }
 }
}

//Search function
void kmp_search(string S, string W)
{
 
 int m = 0; 
 int i = 0;
 int sizeS = S.length();
 int sizeW = W.length();
 
 int *T = new int[sizeof(int) * sizeW];
 
 kmp_table(W, T);
 
 while( (m + i) &amp;lt; sizeS)
 {
  if (W[i] == S[m + i]) 
  {
            if (i == (sizeW - 1))
            {
             //Add the start index of match in the FOUND table
             FOUND[l++] = m;
   }
    
            i++;
        }
        else
        {
            if (T[i] &amp;gt; -1)
            {
                m = m + i - T[i];
    i = T[i];
            }
            else
            {
                m = m + 1;
    i = 0;
            }
        }
 }
 
 delete(T);
}

int main()
{
 string S = &quot;ABCDBCAAB ABCDABCDABDE ABCDABD&quot;;
 string W = &quot;ABCD&quot;;
 
 kmp_search(S,W);
  
 for (int i = 0 ; i &amp;lt; l; i++)
  cout&amp;lt;&amp;lt;&quot;Pattern found at &quot;&amp;lt;&amp;lt; FOUND[i] &amp;lt;&amp;lt;endl; 
}

&lt;/code&gt;
&lt;/pre&gt;

&lt;/div&gt;
</description><link>http://simplestcodings.blogspot.com/2016/09/string-matching-using-kmp-algorithm.html</link><author>noreply@blogger.com (Varun)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhIwpmFSXZ6fIPZNZRO_GMMSp0twPbWaElt80nRNVFZxdzK_OC9JvFqWlraiHqzCg2nwli5n5BzlJF0vUM9hI0IO1lwucGc4FuoqjQyQvWFPT_XikUBqorSYA9tZc18cryOP-0E4Gir2kXjupPpTfP-zbaca6KPfq97w4lVWiTPpTVIaEJVILk_ElQz0Wo/s72-w425-h213-c/kmp.png" height="72" width="72"/><thr:total>1</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-3459284654925679524.post-6827868451772052062</guid><pubDate>Tue, 24 Feb 2015 12:22:00 +0000</pubDate><atom:updated>2023-12-20T21:31:17.592+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">COM</category><category domain="http://www.blogger.com/atom/ns#">Component Object Model</category><title>Component Object Model(COM) - Implementation in C++ -- Usage in C++, C#</title><description>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
As per &lt;a href=&quot;https://msdn.microsoft.com/en-US/library/727z646z(v=vs.80).aspx&quot; target=&quot;_blank&quot;&gt;Microsoft &lt;/a&gt;&quot;Component Object Model or COM is a platform-independent, distributed, object-oriented system for creating binary software components that can interact&quot;.&lt;br /&gt;
COM defines a standard (Object Model) and the implementation part is left to the developer. These objects can communicate within a process or across the processes, &amp;nbsp;on the same or different machine with different programming languages.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;&lt;u&gt;Language requirement for COM :&lt;/u&gt;&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
1. Ability to create structures of pointers&lt;br /&gt;
&lt;br /&gt;
2. Ability to call functions using pointers&lt;br /&gt;
&lt;br /&gt;
Object-oriented languages such as C++ and Smalltalk provide programming mechanisms that simplify the implementation of COM objects, but languages such as C, Java, and VBScript can be used create and use COM objects.&lt;br /&gt;
&lt;br /&gt;
Object&#39;s data is accessed using interfaces. The functions of this interface are called methods. The pointers to these interfaces enables to call the methods.&lt;br /&gt;
&lt;br /&gt;
More information on COM is available at the &lt;a href=&quot;https://msdn.microsoft.com/en-us/library/ms694363(v=vs.85).aspx&quot; target=&quot;_blank&quot;&gt;MSDN &lt;/a&gt;.&lt;br /&gt;
&lt;br /&gt;
In a nutshell , COM provides interfaces which can be implemented in different languages and can be used over distributed platforms.&lt;br /&gt;
&lt;br /&gt;
To provide portability across platforms and programming languages, COM uses interface definition in platform-independent language, IDL(Interface Definition Language).&lt;br /&gt;
&lt;br /&gt;
&lt;h1&gt;
Steps involved to create COM interface:&lt;/h1&gt;
&lt;ol style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;Define the interface/s in .idl file.&lt;/li&gt;
&lt;li&gt;Compile the .idl file using IDL compiler(platform and language specific) to generate language and platform specific code.&lt;/li&gt;
&lt;li&gt;Implement these interface/s in the specific language.&lt;/li&gt;
&lt;li&gt;Use it.&lt;/li&gt;
&lt;/ol&gt;
&lt;br /&gt;
&lt;br /&gt;
In our example, we are using MIDL compiler to generate the C++ specific code and DLL.&lt;br /&gt;
We will use ATL to make the implementation easier. ATL is the Active Template Library, a set of template-based C++ classes with which you can easily create small, fast Component Object Model (COM) objects. It has special support for key COM features including: stock implementations of IUnknown, IClassFactory, IClassFactory2, and IDispatch; dual interfaces; standard COM enumerator interfaces; connection points; tear-off interfaces; and ActiveX controls.&lt;br /&gt;
&lt;br /&gt;
We are using Visual Studio 2005 for our example. Visual Studio provides ATL project wizard which will help a lot and make the process easy.&lt;br /&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;h1&gt;
Steps to generate COM DLL:&lt;/h1&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;/div&gt;
&lt;ol style=&quot;text-align: left;&quot;&gt;
&lt;li&gt; Create a new project in Visual Studio File-&amp;gt;New-&amp;gt;Project-&amp;gt;Visual C++ -&amp;gt; ATL =&amp;gt; ATL Project.&lt;br /&gt;
&lt;table align=&quot;center&quot; cellpadding=&quot;0&quot; cellspacing=&quot;0&quot; class=&quot;tr-caption-container&quot; style=&quot;margin-left: auto; margin-right: auto; text-align: center;&quot;&gt;&lt;tbody&gt;
&lt;tr&gt;&lt;td style=&quot;text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh6yqSej_8a02tGwMDFY9X68wNgF-kw653tYeNBYst1NqcuCHg2GfJNxmXnz1Dejm1MmMEKHuwrZqGtEWA6kR5K1HpBGhRBT0otakfOhgZ4xpYUenhWePUG9qnudK2FDSzU965g1HxG494/s1600/1.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: auto; margin-right: auto;&quot;&gt;&lt;img alt=&quot;New Project&quot; border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh6yqSej_8a02tGwMDFY9X68wNgF-kw653tYeNBYst1NqcuCHg2GfJNxmXnz1Dejm1MmMEKHuwrZqGtEWA6kR5K1HpBGhRBT0otakfOhgZ4xpYUenhWePUG9qnudK2FDSzU965g1HxG494/s1600/1.png&quot; height=&quot;427&quot; title=&quot;New Project&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td class=&quot;tr-caption&quot; style=&quot;text-align: center;&quot;&gt;&lt;br /&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;br /&gt;
&lt;/li&gt;
&lt;li&gt; Give the project name as Calculator as we will be implementing a calculator interface using COM.
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj1ljRaRxKTY5fCwDwP5i9cBlONn3kOZqpuCliWUBaniMgEu_32JQv_nspfpwUjxmO33SyFv4tL9N7NCdYfF98t6vP6faV5US0qMEmzKOYxoRe_nrZjMafeicNWRO3o87_9KjRzBsMxpnE/s1600/2.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img alt=&quot;ATL Project&quot; border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj1ljRaRxKTY5fCwDwP5i9cBlONn3kOZqpuCliWUBaniMgEu_32JQv_nspfpwUjxmO33SyFv4tL9N7NCdYfF98t6vP6faV5US0qMEmzKOYxoRe_nrZjMafeicNWRO3o87_9KjRzBsMxpnE/s1600/2.png&quot; height=&quot;451&quot; title=&quot;ATL Project&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;/li&gt;
&lt;li&gt; Choose DLL(Dynamic-link library) in the Application Settings -&amp;gt; Finish.
&lt;br /&gt;&lt;br /&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjGaXlrOqjXIMDeQMEnPyIyeUBdxU_BboLrsUHIHNqGU5KwyyeXl8qAVhl748LUh51MqcqVEByIL7_Q8tFfTa54NVnmSnIhvQ0a9DH5y29hKYB5SpVxTCQEfWZHj0uNuI1317Fmo7Uj9O8/s1600/3.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img alt=&quot;Application Settings&quot; border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjGaXlrOqjXIMDeQMEnPyIyeUBdxU_BboLrsUHIHNqGU5KwyyeXl8qAVhl748LUh51MqcqVEByIL7_Q8tFfTa54NVnmSnIhvQ0a9DH5y29hKYB5SpVxTCQEfWZHj0uNuI1317Fmo7Uj9O8/s1600/3.png&quot; height=&quot;451&quot; title=&quot;Application Settings&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;/li&gt;
&lt;li&gt; This structure will be visible once the project is created.
&lt;br /&gt;&lt;br /&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjUcJIisASDv8LQgxu4qAsfzppLqfq6joRM-J6swLH7VNbTWSu_2i4RAbVKAdE0Fh049qi_Ksziz0TYkTjVX7tlxVgptk7j2IYKs3VolR8VjAXZ8Zw-F4pgKWaafx1q_-ZuZKHsjppNY-4/s1600/4.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img alt=&quot;Project Structure&quot; border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjUcJIisASDv8LQgxu4qAsfzppLqfq6joRM-J6swLH7VNbTWSu_2i4RAbVKAdE0Fh049qi_Ksziz0TYkTjVX7tlxVgptk7j2IYKs3VolR8VjAXZ8Zw-F4pgKWaafx1q_-ZuZKHsjppNY-4/s1600/4.png&quot; height=&quot;640&quot; title=&quot;Project Structure&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;/li&gt;
&lt;li&gt; Now add a class following the image as below. Right click on the project Add-&amp;gt;Class.
&lt;br /&gt;&lt;br /&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh65oWzyImC1SfcE_tCp2XmPCkKCvFnRbxLFACgvsop6G5aL6wt0EqTRxfgvfJq0HS51gFk6JhWIt0tOXXuUS9R6AQxMLxmvSTpQ4oyMzPdL9yDI4C4WCpYvvAzfMH6RQVACAfgIhscgRQ/s1600/5.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img alt=&quot;Add COM Object&quot; border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh65oWzyImC1SfcE_tCp2XmPCkKCvFnRbxLFACgvsop6G5aL6wt0EqTRxfgvfJq0HS51gFk6JhWIt0tOXXuUS9R6AQxMLxmvSTpQ4oyMzPdL9yDI4C4WCpYvvAzfMH6RQVACAfgIhscgRQ/s1600/5.png&quot; height=&quot;640&quot; title=&quot;Add COM Object&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;/li&gt;
&lt;li&gt; We will now add a COM Object using ATL Simple Object. 
&lt;br /&gt;&lt;br /&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEha1HPieDqnC8WB0ZITEWu4xAm4t-s-HeZf6fQxp3ovUaBih-nQV8BFdsYk4C7BiHcrrA5n5lYia3EX2CNxgU8NK1wXO4oaodjSPusAFWdVNB_zF6IOSFp42lbYH6Zywe-ba8D05B4t5Do/s1600/6.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img alt=&quot;Add COM Object&quot; border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEha1HPieDqnC8WB0ZITEWu4xAm4t-s-HeZf6fQxp3ovUaBih-nQV8BFdsYk4C7BiHcrrA5n5lYia3EX2CNxgU8NK1wXO4oaodjSPusAFWdVNB_zF6IOSFp42lbYH6Zywe-ba8D05B4t5Do/s1600/6.png&quot; height=&quot;404&quot; title=&quot;Add COM Object&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;

&lt;/li&gt;
&lt;li&gt; Give the name of class as CalculatorImpl (This defines the implentation of the interface). You can see under the panel C++ these four areas are updated -&amp;gt; Short Name, .h file, Class, .cpp file to be as CalculatorImpl, CalculatorImpl.h , CCalculatorImpl and CalculatorImpl.cpp respectively .

Also in the panel COM below, these four areas are also updated - CoClass, Type, Interface and ProgID.
Change these according to the image below.
&lt;br /&gt;&lt;br /&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiNXbDoAlQRRa1gGqypfXnKR_uVOHxd11pS63qhalXBsSeGG-hYu4-7UYr-J49xU8BunZGSnNfGlZr0WRoy6k5xKg5OXN8ubxcvFuZ8mbF3aqwWw-IrycOGMFSNdj70qJgtkIxNvnhLaFU/s1600/7.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img alt=&quot;ATL Simple Object Wizard&quot; border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiNXbDoAlQRRa1gGqypfXnKR_uVOHxd11pS63qhalXBsSeGG-hYu4-7UYr-J49xU8BunZGSnNfGlZr0WRoy6k5xKg5OXN8ubxcvFuZ8mbF3aqwWw-IrycOGMFSNdj70qJgtkIxNvnhLaFU/s1600/7.png&quot; height=&quot;449&quot; title=&quot;ATL Simple Object Wizard&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;

&lt;/li&gt;
&lt;li&gt; Choose the Options for the COM Object as below, then click on Finish.
&lt;br /&gt;&lt;br /&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEguno3pq_i-HZBKComuW3qtHPxGO_i1IJrTf4VxZ8mFP3C4qUBl_129m2t5jDOFje_YhoBkjOZb2G3JkxHMukg_GUiZAcnB1xeuKi2qOHUDL9RfgLbVITHND23uMd8SfhmF8FaS_hI7KAU/s1600/8.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img alt=&quot;ATL Simple Object Wizard - Options&quot; border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEguno3pq_i-HZBKComuW3qtHPxGO_i1IJrTf4VxZ8mFP3C4qUBl_129m2t5jDOFje_YhoBkjOZb2G3JkxHMukg_GUiZAcnB1xeuKi2qOHUDL9RfgLbVITHND23uMd8SfhmF8FaS_hI7KAU/s1600/8.png&quot; height=&quot;451&quot; title=&quot;ATL Simple Object Wizard - Options&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;

&lt;/li&gt;
&lt;li&gt; After these changes, the Calculator.idl file will look like this:

&lt;br /&gt;&lt;br /&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhK9Jgg8WTHUmW1If42_X2YMaVQ3QshMTAPcOiiKJtBMq3LgK5I19a49LS_Wa5gknXWFXPYkW4U7dyLijsaXQf2KBvAUi2cx_346MtHxrjgXQkGmpXi9BeKSD9QO0-H4FX74gy-amlKHqU/s1600/9.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img alt=&quot;Calculator.idl&quot; border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhK9Jgg8WTHUmW1If42_X2YMaVQ3QshMTAPcOiiKJtBMq3LgK5I19a49LS_Wa5gknXWFXPYkW4U7dyLijsaXQf2KBvAUi2cx_346MtHxrjgXQkGmpXi9BeKSD9QO0-H4FX74gy-amlKHqU/s1600/9.png&quot; height=&quot;456&quot; title=&quot;Calculator.idl&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;

&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Here, the declaration for interface ICalculator is added. ICalculator implements IDispatch interface. IDispatch is the interface that exposes the OLE Automation protocol. It is one of the standard interfaces exposed by COM. The IDispatch interface inherits from the IUnknown interface. More information on IDispatch can be found &lt;a href=&quot;https://msdn.microsoft.com/en-us/library/windows/desktop/ms221608(v=vs.85).aspx&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt;.&amp;nbsp;You can also see the declaration of the Type Library CalculatorLib which declares a coclass Calculator as well. This CoClass creates a COM object, which can implement a COM interface.
 The Type library information helps in creating .tlb file which is a binary file that stores information about a COM or DCOM object&#39;s properties and methods in a form that is accessible to other applications at runtime. Using a type library, an application or browser can determine which interfaces an object supports, and invoke an object&#39;s interface methods. This can occur even if the object and client applications were written in different programming languages. The COM/DCOM run-time environment can also use a type library to provide automatic cross-apartment, cross-process, and cross-machine marshaling for interfaces described in type libraries.&lt;br /&gt;&lt;/li&gt;
&lt;li&gt; Now our interface is ready to have some methods. Switch to Class View beside Solution Explorer as shown in image below. Right click on ICalculator interface and add a method. Add-&amp;gt;Add Method.
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiXWOxY-FkFmwpQ8hTOdUMBr1aOWxY-NDhvkZAEPLMdW6FOyO8dS9zTEfwge4kkxFqcvSqEAi_WZoOhnmL66l4qL5Qzd8b-TSuX-KJ4RW97dQqPz0kmvIEuz-Z07mNtKJKjL2j5PWqREmQ/s1600/10.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img alt=&quot;Add Methods&quot; border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiXWOxY-FkFmwpQ8hTOdUMBr1aOWxY-NDhvkZAEPLMdW6FOyO8dS9zTEfwge4kkxFqcvSqEAi_WZoOhnmL66l4qL5Qzd8b-TSuX-KJ4RW97dQqPz0kmvIEuz-Z07mNtKJKjL2j5PWqREmQ/s1600/10.png&quot; height=&quot;640&quot; title=&quot;Add Methods&quot; width=&quot;276&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;

&lt;/li&gt;
&lt;li&gt; Give the method name as Add , check parameter attributes as &#39;in&#39;, parameter type DOUBLE, parameter name as Input1. Click on Add. You should see the parameter being added to the list box. Similarly add one more input parameter named Input2. Now add an output parameter with parameter type DOUBLE*, parameter name as pOutput, check parameter attributes as &#39;out&#39; and &#39;retval&#39;. Click on Add. 

Click on Next-&amp;gt;Finish.

&lt;br /&gt;&lt;br /&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiog3XlUBxUW_xIzlhGXpTMQMFaA37khEgH6VM32N6vp-J4Iq_TqzJdHLDDkrNCs4G1TaaRepkHKqamoKSLyMJVAdUVBK81FO-pxVfQ8sfNg9ZXEgR1_FwPsJKm2OcowESJKbe3yBvDwbU/s1600/11.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img alt=&quot;Add Method Wizard - Add Input&quot; border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiog3XlUBxUW_xIzlhGXpTMQMFaA37khEgH6VM32N6vp-J4Iq_TqzJdHLDDkrNCs4G1TaaRepkHKqamoKSLyMJVAdUVBK81FO-pxVfQ8sfNg9ZXEgR1_FwPsJKm2OcowESJKbe3yBvDwbU/s1600/11.png&quot; height=&quot;451&quot; title=&quot;Add Method Wizard - Add Input&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;

&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjKKogM2H1FfcSvTAdt4rY6E6hUtsc3OAoiiyxQrSgnGyKlTUYw7LcPpElrB50LKE-y1Z3KUi2hem1uaO5Rgp5x5gD3X84e3P4VUhkBKfkBsBB1G0EN3WyFyjKgcT95EitpgiLTVTFYEzI/s1600/12.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img alt=&quot;Add Method Wizard - Add Output&quot; border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjKKogM2H1FfcSvTAdt4rY6E6hUtsc3OAoiiyxQrSgnGyKlTUYw7LcPpElrB50LKE-y1Z3KUi2hem1uaO5Rgp5x5gD3X84e3P4VUhkBKfkBsBB1G0EN3WyFyjKgcT95EitpgiLTVTFYEzI/s1600/12.png&quot; height=&quot;452&quot; title=&quot;Add Method Wizard - Add Output&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhio8AQjsTzRHlQoG4s1KDnB_r0j5JUGxa87PQPLBd8N9tb-bSsVUfnelhB1FBHMRNzqg13ExEnyEm-9dYY7iYHJvRGmDPpMDpsZxEDtv5N9G0C0M0ROxrLblbVKCVEQAROMXbnBavNPds/s1600/13.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img alt=&quot;IDL Attributes&quot; border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhio8AQjsTzRHlQoG4s1KDnB_r0j5JUGxa87PQPLBd8N9tb-bSsVUfnelhB1FBHMRNzqg13ExEnyEm-9dYY7iYHJvRGmDPpMDpsZxEDtv5N9G0C0M0ROxrLblbVKCVEQAROMXbnBavNPds/s1600/13.png&quot; height=&quot;449&quot; title=&quot;IDL Attributes&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;

Similarly add three more methods Subtract, Multiply and Divide.&lt;br /&gt;&lt;br /&gt;
&lt;/li&gt;
&lt;li&gt; After adding the methods , you should see the functions&#39; skeleton created in Calculator.idl and CalculatorImpl.cpp like this :&lt;br /&gt;&lt;br /&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgYeW6AxVJd0JNShJCWpPCl7b6O3L3hrQF150G8MPeyFmrKZiG1dQ2KLM0CySwmCehwrCImwfVdWEyrVJ9XU4lfvzSqZYfZBKyh03xG4YrMROGAeIWbyQUyTUvJJwefOPxhbp6PFVy4noI/s1600/14.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img alt=&quot;Calculator.idl&quot; border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgYeW6AxVJd0JNShJCWpPCl7b6O3L3hrQF150G8MPeyFmrKZiG1dQ2KLM0CySwmCehwrCImwfVdWEyrVJ9XU4lfvzSqZYfZBKyh03xG4YrMROGAeIWbyQUyTUvJJwefOPxhbp6PFVy4noI/s1600/14.png&quot; height=&quot;387&quot; title=&quot;Calculator.idl&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjeV5bxzyRloaM7gr_IKqj0lgRk-oTrCwq9vOT8mrYhmN3UedNlghvLRBfizucT0ertZf31WxkDhIi_TiCGWgi1yWum3-qiYyNPWpmAEzihQz0P4ptwywk-mmPHpRp5eTFL8YBgcpwYtF8/s1600/15.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img alt=&quot;CalculatorImpl.cpp&quot; border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjeV5bxzyRloaM7gr_IKqj0lgRk-oTrCwq9vOT8mrYhmN3UedNlghvLRBfizucT0ertZf31WxkDhIi_TiCGWgi1yWum3-qiYyNPWpmAEzihQz0P4ptwywk-mmPHpRp5eTFL8YBgcpwYtF8/s1600/15.png&quot; height=&quot;507&quot; title=&quot;CalculatorImpl.cpp&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;/li&gt;
&lt;li&gt; We will add the implementation in the skeleton.

&lt;/li&gt;
&lt;li&gt; Now compile the solution. It will generate Calculator.dll in the project output directory (e.g. for 64 bit Release configuration it is %PROJECT_HOME%\Calculator\Calculator\x64\Release by default) &lt;/li&gt;
&lt;/ol&gt;
Now we have our COM DLL. To use it , we need some code.&lt;br /&gt;
&lt;br /&gt;
&lt;h1&gt;
Steps to create sample C++ code to test COM DLL:&lt;/h1&gt;
&lt;ol style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;Create an Empty Win32 Console Project in Visual Studio 
&lt;br /&gt;&lt;br /&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiPOFCgc2n_UEuu_RW7Fjs8sqaO5TTB7jSW5fZnjwRsmHMOjWZ35FzrCCBwYHLVdhcgm7vltvEE_we1pqyPIOOTMnU0nN-c1wZGhvftXmTXUOf0UHX-MXz9OcX5SIVFb9Vq_1tPU9oioK8/s1600/t1.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img alt=&quot;Create Win32 Project&quot; border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiPOFCgc2n_UEuu_RW7Fjs8sqaO5TTB7jSW5fZnjwRsmHMOjWZ35FzrCCBwYHLVdhcgm7vltvEE_we1pqyPIOOTMnU0nN-c1wZGhvftXmTXUOf0UHX-MXz9OcX5SIVFb9Vq_1tPU9oioK8/s1600/t1.png&quot; height=&quot;451&quot; title=&quot;Create Win32 Project&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;

&lt;/li&gt;
&lt;li&gt; Create an Empty cpp file in the project (TestCalc.cpp)
&lt;br /&gt;&lt;br /&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEinFJFYyvDYFe2ZXYSEZ3VNDpHRPIiTsoK0iEgy45c-XmZStyBm0QsT0xdLVt6J-cnbqrH6upbXaDPc5HpAs9CL4d5ZBDhiO5zPxoMXai5hOgKjVdox5TFD1UY5owNqVtbHDDRNo_JqAU0/s1600/t2.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img alt=&quot;Create Win32 Project - Application Settings&quot; border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEinFJFYyvDYFe2ZXYSEZ3VNDpHRPIiTsoK0iEgy45c-XmZStyBm0QsT0xdLVt6J-cnbqrH6upbXaDPc5HpAs9CL4d5ZBDhiO5zPxoMXai5hOgKjVdox5TFD1UY5owNqVtbHDDRNo_JqAU0/s1600/t2.png&quot; height=&quot;451&quot; title=&quot;Create Win32 Project - Application Settings&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;

&lt;/li&gt;
&lt;li&gt; Add the path to Calculator.h in Additional Include Directories in the project properties. Right click project -&amp;gt; Properties -&amp;gt; Configuration Properties -&amp;gt; C/C++ -&amp;gt; General.
&lt;br /&gt;&lt;br /&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj9vm1mO-n9aqZK_2OIKUzABbHpia_Gw_EosyKVE6ADXr8oFdRUd-zoEvjpCrDwsMKfdFXPQJ0Pwts352gYAUaFFbsAOKl8dK-2SCYxdYophT3B60NC6B8YgFRr7VRzdatdB60ffZ13SYY/s1600/t3.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img alt=&quot;Add Additional Includes&quot; border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj9vm1mO-n9aqZK_2OIKUzABbHpia_Gw_EosyKVE6ADXr8oFdRUd-zoEvjpCrDwsMKfdFXPQJ0Pwts352gYAUaFFbsAOKl8dK-2SCYxdYophT3B60NC6B8YgFRr7VRzdatdB60ffZ13SYY/s1600/t3.png&quot; height=&quot;448&quot; title=&quot;Add Additional Includes&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;/li&gt;
&lt;li&gt; Add Calculator_i.c in the Project Source.
&lt;br /&gt;&lt;br /&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiusGkpG7ua-C1RaMlU10DgWPwyolYk3c8Wm4JCLvS7qYnh_l97vjvsNTJvJoGcAtnZRpYR0ESLoVrH4IzKp0DZNF6BMMGp0AGahgdjZhlyCCFUE08vsopNxnYNjqKZnJfBqhwu2Tplo-w/s1600/t4.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img alt=&quot;Add _i.c file&quot; border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiusGkpG7ua-C1RaMlU10DgWPwyolYk3c8Wm4JCLvS7qYnh_l97vjvsNTJvJoGcAtnZRpYR0ESLoVrH4IzKp0DZNF6BMMGp0AGahgdjZhlyCCFUE08vsopNxnYNjqKZnJfBqhwu2Tplo-w/s1600/t4.png&quot; height=&quot;640&quot; title=&quot;Add _i.c file&quot; width=&quot;459&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;/li&gt;
&lt;li&gt; Populate TestCalc.cpp with the contents given later in the blog post.&lt;/li&gt;
&lt;li&gt; Run the executable(F5).&lt;/li&gt;
&lt;/ol&gt;
&lt;br /&gt;
Note: One advantage using the Visual Studio to build our COM dll was that it registers the COM DLL by default. So we do not need to do it manually. This is the reason why we are able to run the test code even without the DLL being present in the System Path or adding it&#39;s path to PATH environment variable .&lt;br /&gt;
&lt;br /&gt;
Now as we have been saying that the COM is interoperable between the languages/platform etc. Let&#39;s see some code in action.&lt;br /&gt;
We are going to use the COM DLL generated in C# application.&lt;br /&gt;
&lt;br /&gt;
Before we go on using DLLs directly , let&#39;s be SMART and create .NET wrappers over COM DLL. Now you would ask what&#39;s that ??&lt;br /&gt;
&lt;br /&gt;
The COM components has unmanaged code while .NET framework has managed code. Data types, method signatures, and error-handling mechanisms vary between managed and unmanaged object models&lt;br /&gt;
Code that executes under the control of the runtime is called managed code and the code that runs outside the runtime is called unmanaged code.&lt;br /&gt;
&lt;br /&gt;
To simplify this, .NET wrappers are generated over existing COM components which allows unmanaged model to be converted to managed.&lt;br /&gt;
More information in this &lt;a href=&quot;https://msdn.microsoft.com/en-us/library/5dxz80y2(v=vs.110).aspx&quot; target=&quot;_blank&quot;&gt;link&lt;/a&gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;h1&gt;
Steps to create .NET wrapper from COM DLL:&lt;/h1&gt;
&lt;span class=&quot;Apple-tab-span&quot; style=&quot;white-space: pre;&quot;&gt; &lt;/span&gt;Run this command from the output directory:&lt;br /&gt;
&lt;br /&gt;
&lt;div&gt;
&lt;pre class=&quot;brush:cpp&quot;&gt;     tlbimp /machine: x64 Calculator.dll /out: Calculator_Wrapper.dll

&lt;/pre&gt;
&lt;/div&gt;
&lt;span class=&quot;Apple-tab-span&quot; style=&quot;white-space: pre;&quot;&gt; &lt;/span&gt;It will generate Calculator_Wrapper.dll which is nothing but our .NET wrapper over COM.&lt;br /&gt;
&lt;span class=&quot;Apple-tab-span&quot; style=&quot;white-space: pre;&quot;&gt; &lt;/span&gt;&lt;br /&gt;
&lt;h1&gt;
Steps to create C# application to test COM DLL :&lt;/h1&gt;
&lt;br /&gt;
&lt;ol style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;Create a Windows Application TestCalcCCharp from Visual Studio
&lt;br /&gt;&lt;br /&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhcQg6EKdU5XBeGBJjlnm6Q5_IdQk7Jubpvd6DhylpXHh1K4UcCLF78GpSWXQpT-vkaxx6xIf2Z0TjVGD5xmhZC2yF2QncKfSMZNSZpfT_6wKvEKzwF6F8JaTGNxek64yaItO8E-Z1gadA/s1600/cs1.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img alt=&quot;Create Winform Application &quot; border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhcQg6EKdU5XBeGBJjlnm6Q5_IdQk7Jubpvd6DhylpXHh1K4UcCLF78GpSWXQpT-vkaxx6xIf2Z0TjVGD5xmhZC2yF2QncKfSMZNSZpfT_6wKvEKzwF6F8JaTGNxek64yaItO8E-Z1gadA/s1600/cs1.png&quot; height=&quot;428&quot; title=&quot;Create Winform Application &quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;

&lt;/li&gt;
&lt;li&gt;Add a reference to the wrapper Calculator_Wrapper.dll
&lt;br /&gt;&lt;br /&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiyO9vsFHe0zjEzy1tpeH-9b9mNYkuuMLHTOO2dhldvoZcO05_ghTkldYHARrwQ67l8N6PK0nGRohNU66IFBZQlvaLVsg6yXTYBNblLWAkadpteo-WbJ0Xl72gayBXWiuptPCx4p_IdpdM/s1600/cs2.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img alt=&quot;Add reference&quot; border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiyO9vsFHe0zjEzy1tpeH-9b9mNYkuuMLHTOO2dhldvoZcO05_ghTkldYHARrwQ67l8N6PK0nGRohNU66IFBZQlvaLVsg6yXTYBNblLWAkadpteo-WbJ0Xl72gayBXWiuptPCx4p_IdpdM/s1600/cs2.png&quot; height=&quot;640&quot; title=&quot;Add reference&quot; width=&quot;436&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;


&lt;/li&gt;
&lt;li&gt;Create a simple form as per the code in the blog post.
&lt;br /&gt;&lt;br /&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiDKn_3NJ5lt4ju4oNNIz4wQHXOSMuuwUGVW5fcXvT5_P22rgyP9M3zkYnx8-BQrHuIIDZ-HbfKQ8JUEHQRWXiQnAGSTgdw-itSU5DWfLUtGzsyIWo78cYdTi0PE8TTiwbGBuvoP8Nv1ik/s1600/cs3.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img alt=&quot;Winform &quot; border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiDKn_3NJ5lt4ju4oNNIz4wQHXOSMuuwUGVW5fcXvT5_P22rgyP9M3zkYnx8-BQrHuIIDZ-HbfKQ8JUEHQRWXiQnAGSTgdw-itSU5DWfLUtGzsyIWo78cYdTi0PE8TTiwbGBuvoP8Nv1ik/s1600/cs3.png&quot; height=&quot;530&quot; title=&quot;Winform &quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;/li&gt;
&lt;li&gt;Populate the functions to call the methods from COM.&lt;/li&gt;
&lt;/ol&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;
&lt;code class=&quot;language-cpp&quot;&gt;

// CalculatorImpl.cpp : Implementation of CCalculatorImpl

#include &quot;stdafx.h&quot;
#include &quot;CalculatorImpl.h&quot;

// CCalculatorImpl

STDMETHODIMP CCalculatorImpl::Add(DOUBLE Input1, DOUBLE Input2, DOUBLE* pOutput)
{
 *pOutput = Input1 + Input2;

 return S_OK;
}

STDMETHODIMP CCalculatorImpl::Subtract(DOUBLE Input1, DOUBLE Input2, DOUBLE* pOutput)
{
 *pOutput = Input1 - Input2;
 
 return S_OK;
}

STDMETHODIMP CCalculatorImpl::Multiply(DOUBLE Input1, DOUBLE Input2, DOUBLE* pOutput)
{
 *pOutput = Input1 * Input2;

 return S_OK;
}

STDMETHODIMP CCalculatorImpl::Divide(DOUBLE Input1, DOUBLE Input2, DOUBLE* pOutput)
{
 *pOutput = Input1 / Input2;

 return S_OK;
}

&lt;/code&gt;
&lt;/pre&gt;
&lt;/div&gt;


&lt;pre class=&quot;prettyprint&quot;&gt;
&lt;code class=&quot;language-cpp&quot;&gt;

//TestCalc.cpp
#include &quot;Calculator.h&quot;
#include &amp;lt;iostream&amp;gt;
#include &amp;lt;stdexcept&amp;gt;
using std::runtime_error; 

int main()
{
 HRESULT hr ;
 ICalculator      *calc = NULL;

 hr = CoInitialize(0);

 if(SUCCEEDED(hr))
    {
  hr = CoCreateInstance( CLSID_Calculator, NULL, 
            CLSCTX_INPROC_SERVER,
   IID_ICalculator, (void**) &amp;amp;calc);

        // If we succeeded then call the Add 
        // method, if it failed
        // then display an appropriate message to the user.
        if(SUCCEEDED(hr))
        {
            double ReturnValue;
   double a = 4;
   double b = 0;
   calc-&amp;gt;Add(a, b, &amp;amp;ReturnValue);
            std::cout &amp;lt;&amp;lt; &quot;The answer for &quot;&amp;lt;&amp;lt;a&amp;lt;&amp;lt;&quot; + &quot;&amp;lt;&amp;lt;b&amp;lt;&amp;lt;&quot; is: &quot; 
                &amp;lt;&amp;lt; ReturnValue &amp;lt;&amp;lt; std::endl;
            calc-&amp;gt;Release(); 
        }
        else
        {
            std::cout &amp;lt;&amp;lt; &quot;CoCreateInstance Failed.&quot; &amp;lt;&amp;lt; std::endl;
        }
    }
    // Uninitialize COM
    CoUninitialize();

}

&lt;/code&gt;
&lt;/pre&gt;
&lt;/div&gt;
&lt;div&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;
&lt;code class=&quot;language-cpp&quot;&gt;
//Form1.Designer.cs
namespace TestCalcCSharp
{
    partial class Form1
    {
        /// &amp;lt;summary&amp;gt;
        /// Required designer variable.
        /// &amp;lt;/summary&amp;gt;
        private System.ComponentModel.IContainer components = null;

        /// &amp;lt;summary&amp;gt;
        /// Clean up any resources being used.
        /// &amp;lt;/summary&amp;gt;
        /// &amp;lt;param name=&quot;disposing&quot;&amp;gt;true if managed resources should be disposed; otherwise, false.&amp;lt;/param&amp;gt;
        protected override void Dispose(bool disposing)
        {
            if (disposing &amp;amp;&amp;amp; (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// &amp;lt;summary&amp;gt;
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// &amp;lt;/summary&amp;gt;
        private void InitializeComponent()
        {
            this.calcPanel = new System.Windows.Forms.GroupBox();
            this.groupBox1 = new System.Windows.Forms.GroupBox();
            this.logTextBox = new System.Windows.Forms.RichTextBox();
            this.label5 = new System.Windows.Forms.Label();
            this.label4 = new System.Windows.Forms.Label();
            this.label1 = new System.Windows.Forms.Label();
            this.divBtn = new System.Windows.Forms.Button();
            this.subBtn = new System.Windows.Forms.Button();
            this.addBtn = new System.Windows.Forms.Button();
            this.mulBtn = new System.Windows.Forms.Button();
            this.textBox3 = new System.Windows.Forms.TextBox();
            this.textBox2 = new System.Windows.Forms.TextBox();
            this.label3 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.calcPanel.SuspendLayout();
            this.groupBox1.SuspendLayout();
            this.SuspendLayout();
            // 
            // calcPanel
            // 
            this.calcPanel.Controls.Add(this.groupBox1);
            this.calcPanel.Controls.Add(this.label5);
            this.calcPanel.Controls.Add(this.label4);
            this.calcPanel.Controls.Add(this.label1);
            this.calcPanel.Controls.Add(this.divBtn);
            this.calcPanel.Controls.Add(this.subBtn);
            this.calcPanel.Controls.Add(this.addBtn);
            this.calcPanel.Controls.Add(this.mulBtn);
            this.calcPanel.Controls.Add(this.textBox3);
            this.calcPanel.Controls.Add(this.textBox2);
            this.calcPanel.Controls.Add(this.label3);
            this.calcPanel.Controls.Add(this.label2);
            this.calcPanel.Controls.Add(this.textBox1);
            this.calcPanel.Location = new System.Drawing.Point(13, 13);
            this.calcPanel.Name = &quot;calcPanel&quot;;
            this.calcPanel.Size = new System.Drawing.Size(450, 344);
            this.calcPanel.TabIndex = 0;
            this.calcPanel.TabStop = false;
            this.calcPanel.Text = &quot;Calculator&quot;;
            // 
            // groupBox1
            // 
            this.groupBox1.Controls.Add(this.logTextBox);
            this.groupBox1.Location = new System.Drawing.Point(6, 238);
            this.groupBox1.Name = &quot;groupBox1&quot;;
            this.groupBox1.Size = new System.Drawing.Size(438, 100);
            this.groupBox1.TabIndex = 34;
            this.groupBox1.TabStop = false;
            this.groupBox1.Text = &quot;Logs&quot;;
            // 
            // logTextBox
            // 
            this.logTextBox.Location = new System.Drawing.Point(6, 19);
            this.logTextBox.Name = &quot;logTextBox&quot;;
            this.logTextBox.Size = new System.Drawing.Size(432, 81);
            this.logTextBox.TabIndex = 33;
            this.logTextBox.Text = &quot;&quot;;
            // 
            // label5
            // 
            this.label5.AutoSize = true;
            this.label5.Location = new System.Drawing.Point(254, 22);
            this.label5.Name = &quot;label5&quot;;
            this.label5.Size = new System.Drawing.Size(37, 13);
            this.label5.TabIndex = 32;
            this.label5.Text = &quot;Result&quot;;
            // 
            // label4
            // 
            this.label4.AutoSize = true;
            this.label4.Location = new System.Drawing.Point(163, 22);
            this.label4.Name = &quot;label4&quot;;
            this.label4.Size = new System.Drawing.Size(37, 13);
            this.label4.TabIndex = 31;
            this.label4.Text = &quot;Input2&quot;;
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(83, 22);
            this.label1.Name = &quot;label1&quot;;
            this.label1.Size = new System.Drawing.Size(37, 13);
            this.label1.TabIndex = 30;
            this.label1.Text = &quot;Input1&quot;;
            // 
            // divBtn
            // 
            this.divBtn.Font = new System.Drawing.Font(&quot;Microsoft Sans Serif&quot;, 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.divBtn.Location = new System.Drawing.Point(352, 134);
            this.divBtn.Name = &quot;divBtn&quot;;
            this.divBtn.Size = new System.Drawing.Size(75, 36);
            this.divBtn.TabIndex = 29;
            this.divBtn.Text = &quot;Divide&quot;;
            this.divBtn.UseVisualStyleBackColor = true;
            this.divBtn.Click += new System.EventHandler(this.divBtn_Click);
            // 
            // subBtn
            // 
            this.subBtn.Font = new System.Drawing.Font(&quot;Microsoft Sans Serif&quot;, 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.subBtn.Location = new System.Drawing.Point(125, 134);
            this.subBtn.Name = &quot;subBtn&quot;;
            this.subBtn.Size = new System.Drawing.Size(75, 36);
            this.subBtn.TabIndex = 28;
            this.subBtn.Text = &quot;Subtract&quot;;
            this.subBtn.UseVisualStyleBackColor = true;
            this.subBtn.Click += new System.EventHandler(this.subBtn_Click);
            // 
            // addBtn
            // 
            this.addBtn.Font = new System.Drawing.Font(&quot;Microsoft Sans Serif&quot;, 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.addBtn.Location = new System.Drawing.Point(14, 134);
            this.addBtn.Name = &quot;addBtn&quot;;
            this.addBtn.Size = new System.Drawing.Size(75, 36);
            this.addBtn.TabIndex = 27;
            this.addBtn.Text = &quot;Add&quot;;
            this.addBtn.UseVisualStyleBackColor = true;
            this.addBtn.Click += new System.EventHandler(this.addBtn_Click);
            // 
            // mulBtn
            // 
            this.mulBtn.Font = new System.Drawing.Font(&quot;Microsoft Sans Serif&quot;, 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.mulBtn.Location = new System.Drawing.Point(239, 134);
            this.mulBtn.Name = &quot;mulBtn&quot;;
            this.mulBtn.Size = new System.Drawing.Size(75, 36);
            this.mulBtn.TabIndex = 26;
            this.mulBtn.Text = &quot;Multiply&quot;;
            this.mulBtn.UseVisualStyleBackColor = true;
            this.mulBtn.Click += new System.EventHandler(this.mulBtn_Click);
            // 
            // textBox3
            // 
            this.textBox3.Enabled = false;
            this.textBox3.Location = new System.Drawing.Point(257, 41);
            this.textBox3.Name = &quot;textBox3&quot;;
            this.textBox3.Size = new System.Drawing.Size(170, 20);
            this.textBox3.TabIndex = 7;
            // 
            // textBox2
            // 
            this.textBox2.Location = new System.Drawing.Point(166, 41);
            this.textBox2.Name = &quot;textBox2&quot;;
            this.textBox2.Size = new System.Drawing.Size(57, 20);
            this.textBox2.TabIndex = 6;
            // 
            // label3
            // 
            this.label3.AutoSize = true;
            this.label3.Font = new System.Drawing.Font(&quot;Microsoft Sans Serif&quot;, 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label3.Location = new System.Drawing.Point(228, 44);
            this.label3.Name = &quot;label3&quot;;
            this.label3.Size = new System.Drawing.Size(16, 17);
            this.label3.TabIndex = 4;
            this.label3.Text = &quot;=&quot;;
            // 
            // label2
            // 
            this.label2.AutoSize = true;
            this.label2.Font = new System.Drawing.Font(&quot;Microsoft Sans Serif&quot;, 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label2.Location = new System.Drawing.Point(146, 44);
            this.label2.Name = &quot;label2&quot;;
            this.label2.Size = new System.Drawing.Size(16, 17);
            this.label2.TabIndex = 3;
            this.label2.Text = &quot;+&quot;;
            // 
            // textBox1
            // 
            this.textBox1.Location = new System.Drawing.Point(83, 41);
            this.textBox1.Name = &quot;textBox1&quot;;
            this.textBox1.Size = new System.Drawing.Size(57, 20);
            this.textBox1.TabIndex = 1;
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(475, 369);
            this.Controls.Add(this.calcPanel);
            this.Name = &quot;Form1&quot;;
            this.Text = &quot;Calculator&quot;;
            this.calcPanel.ResumeLayout(false);
            this.calcPanel.PerformLayout();
            this.groupBox1.ResumeLayout(false);
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.GroupBox calcPanel;
        private System.Windows.Forms.TextBox textBox1;
        private System.Windows.Forms.TextBox textBox3;
        private System.Windows.Forms.TextBox textBox2;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Button mulBtn;
        private System.Windows.Forms.Button divBtn;
        private System.Windows.Forms.Button subBtn;
        private System.Windows.Forms.Button addBtn;
        private System.Windows.Forms.Label label5;
        private System.Windows.Forms.Label label4;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.RichTextBox logTextBox;
        private System.Windows.Forms.GroupBox groupBox1;

    }
}


&lt;/code&gt;
&lt;/pre&gt;

&lt;/div&gt;
&lt;div&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;
&lt;code class=&quot;language-cpp&quot;&gt;
//Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Calculator_Wrapper;
using System.Runtime.InteropServices;

namespace TestCalcCSharp
{
    public partial class Form1 : Form
    {
        Calculator_Wrapper.Calculator calc = null;

        public Form1()
        {
            InitializeComponent();
            calc = new Calculator();
        }

        private void addBtn_Click(object sender, EventArgs e)
        {
            try
            {
                double inp1 = double.Parse(textBox1.Text);
                double inp2 = double.Parse(textBox2.Text);


                double output = calc.Add(inp1, inp2);

                textBox3.Text = output.ToString();
            }
            catch (Exception ex)
            {
                logTextBox.Text = ex.Message;
            }
        }

        private void subBtn_Click(object sender, EventArgs e)
        {
            try
            {
                double inp1 = double.Parse(textBox1.Text);
                double inp2 = double.Parse(textBox2.Text);


                double output = calc.Subtract(inp1, inp2);

                textBox3.Text = output.ToString();
            }
            catch (Exception ex)
            {
                logTextBox.Text = ex.Message;
            }
        }

        private void mulBtn_Click(object sender, EventArgs e)
        {
            try
            {
                double inp1 = double.Parse(textBox1.Text);
                double inp2 = double.Parse(textBox2.Text);

                double output = calc.Multiply(inp1, inp2);

                textBox3.Text = output.ToString();
            }
            catch (Exception ex)
            {
                logTextBox.Text = ex.Message;
            }
        }

        private void divBtn_Click(object sender, EventArgs e)
        {
            try
            {
                double inp1 = double.Parse(textBox1.Text);
                double inp2 = double.Parse(textBox2.Text);

                if (inp2 == 0) throw new DivideByZeroException();
                double output = calc.Divide(inp1, inp2);
                textBox3.Text = output.ToString();
            }
            catch (Exception ex)
            {
                logTextBox.Text = ex.Message + &quot;\n&quot;;
            }
        }
    }
}

&lt;/code&gt;
&lt;/pre&gt;
&lt;/div&gt;

&lt;/div&gt;
</description><link>http://simplestcodings.blogspot.com/2015/02/componentobjectmodelcom.html</link><author>noreply@blogger.com (Varun)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh6yqSej_8a02tGwMDFY9X68wNgF-kw653tYeNBYst1NqcuCHg2GfJNxmXnz1Dejm1MmMEKHuwrZqGtEWA6kR5K1HpBGhRBT0otakfOhgZ4xpYUenhWePUG9qnudK2FDSzU965g1HxG494/s72-c/1.png" height="72" width="72"/><thr:total>6</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-3459284654925679524.post-5234970854753038822</guid><pubDate>Sun, 26 Oct 2014 16:33:00 +0000</pubDate><atom:updated>2023-12-21T00:19:14.594+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">Design Patterns</category><category domain="http://www.blogger.com/atom/ns#">facade design pattern</category><title>Facade design pattern implementation in C++</title><description>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;br /&gt;
&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;br /&gt;
&lt;b&gt;&lt;i&gt;Facade &lt;/i&gt;&lt;/b&gt;means the exterior of any object in general. Facade Design Pattern provides similar functionality as well. It provides a simple interface to a complex system.

Just as we can not tell from the exterior of a building what lies inside it, Facade design pattern provides an interface which hides the internal complexity of a system.
It only exposes the desired interfaces which have to be used by a client. It can be only a small subsystem of the complex system as the client may not need all the functionality of the complex system. Also it could modify the interfaces as well to provide the complete functionality of the system.&lt;br /&gt;
&lt;br /&gt;
&lt;table align=&quot;center&quot; cellpadding=&quot;0&quot; cellspacing=&quot;0&quot; class=&quot;tr-caption-container&quot; style=&quot;margin-left: auto; margin-right: auto; text-align: center;&quot;&gt;&lt;tbody&gt;
&lt;tr&gt;&lt;td style=&quot;text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi1JrJeJkRpdSUZbykBJbaeyiPhZDJu7cRF4Feej_hIkRzpbQzuM71_Z7tGzUO9BW9j2SIyu1657UgZGaq94Eu6_MrA6x9RStN0EZpjC_5AA3u88bltAejru3WgFo8zo5taMUKsTlvXqcM/s1600/facade.png&quot; style=&quot;margin-left: auto; margin-right: auto;&quot;&gt;&lt;img alt=&quot;Facade Design Pattern&quot; border=&quot;0&quot; height=&quot;522&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi1JrJeJkRpdSUZbykBJbaeyiPhZDJu7cRF4Feej_hIkRzpbQzuM71_Z7tGzUO9BW9j2SIyu1657UgZGaq94Eu6_MrA6x9RStN0EZpjC_5AA3u88bltAejru3WgFo8zo5taMUKsTlvXqcM/s1600/facade.png&quot; title=&quot;Facade Design Pattern&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td class=&quot;tr-caption&quot; style=&quot;text-align: center;&quot;&gt;Facade Design Pattern&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;br /&gt;
&amp;nbsp;For our implementation of the Facade Design Pattern, we have chosen example of Online Shopping model. The following diagram represents the relationships and flow between the classes.&lt;br /&gt;
&lt;br /&gt;
&lt;table align=&quot;center&quot; cellpadding=&quot;0&quot; cellspacing=&quot;0&quot; class=&quot;tr-caption-container&quot; style=&quot;margin-left: auto; margin-right: auto; text-align: center;&quot;&gt;&lt;tbody&gt;
&lt;tr&gt;&lt;td style=&quot;text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj2r92vQywDbSqKoUS7vtRQykLQB6VCH3u5LLMIE_5Cx0g8Rqou7xU6CjRZk_dxzgz8_eyMtsCHd7K_NyW0MOLqVZpc2GV99fOqBZtXxswrohMx2_gG5lU4D10QqQC41q8p82zVjCR4_AE/s1600/facademy.png&quot; style=&quot;margin-left: auto; margin-right: auto;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;522&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj2r92vQywDbSqKoUS7vtRQykLQB6VCH3u5LLMIE_5Cx0g8Rqou7xU6CjRZk_dxzgz8_eyMtsCHd7K_NyW0MOLqVZpc2GV99fOqBZtXxswrohMx2_gG5lU4D10QqQC41q8p82zVjCR4_AE/s1600/facademy.png&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td class=&quot;tr-caption&quot; style=&quot;text-align: center;&quot;&gt;Class Diagram for below example&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
The example works like this. OnlineShoppingFacade is the interface which is exposed to the customers (us). It&#39;s just like any portal like Flipkart, Amazon or eBay. Now we do not know what the heck is going behind those websites. All we know is that we have just placed an order and we will get a delivery after a certain period of time. Of course there is a status tracker something like this&lt;/div&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhpEoCPVnQOWUoOHTfdcVX9SRLTDzox80kZLXSeLXAK6Vz9Jp3pWTkigtoej_WTWbkirk8WCNlVKMxjqkaz6oUPXM6zPumlBLyA6Yo1fu4OivoFfqINIG3npDiJnV0I4pgjgzrXebR28ZA/s1600/order.png&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;64&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhpEoCPVnQOWUoOHTfdcVX9SRLTDzox80kZLXSeLXAK6Vz9Jp3pWTkigtoej_WTWbkirk8WCNlVKMxjqkaz6oUPXM6zPumlBLyA6Yo1fu4OivoFfqINIG3npDiJnV0I4pgjgzrXebR28ZA/s1600/order.png&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
But still the intricacies behind the process is hidden away from us. This is the Facade for the Online Shopping Portal.&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
Below is a simplistic implementation just to demo how Facade Design Pattern works using a C++ example.&lt;br /&gt;
&lt;br /&gt;

&lt;h1&gt;Facade Design Pattern Implementation(C++)&lt;/h1&gt;
&lt;b&gt;&lt;u&gt;Update(5th Nov 2014)&lt;/u&gt;&lt;/b&gt;: The code is updated to work on linux platform as well.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;
&lt;code class=&quot;language-cpp&quot;&gt;

#include &amp;lt;iostream&amp;gt;
#include &amp;lt;string&amp;gt;
#ifdef _WIN32
#include &amp;lt;windows.h&amp;gt;
#elif defined __linux__
#include &amp;lt;unistd.h&amp;gt;
#endif

/* Uncomment below line to enable debug logs */
/* #define DEBUG */
 
std::string _stateToStrCourier[]   = { &quot;Received&quot;, &quot;VerifyReachbility&quot;, &quot;AssignPerson&quot;, 
                                       &quot;DispatchPackage&quot;, &quot;GetDeliveryConfirmation&quot;, &quot;Complete&quot;};
std::string _stateToStrVendor[]    = { &quot;Received&quot;, &quot;VerifyInventory&quot;, &quot;GetItemFromWareHouse&quot;, 
                                       &quot;PackItem&quot;, &quot;ContactCourier&quot;, &quot;Complete&quot;};
std::string _stateToStrOrderTeam[] = { &quot;Received&quot;, &quot;VerifyPayment&quot;, &quot;ContactVendor&quot;, &quot;Complete&quot;};

void mySleep(unsigned int millisecs)
{
#ifdef _WIN32
 Sleep(millisecs);
#elif defined __linux__
 usleep(1000 * millisecs);
#endif
}

class Courier
{
public:
 void submitRequestToCourier()
 {
  _state = 0;
 }
 bool checkStatus()
 {
#ifdef DEBUG
  std::cout&amp;lt;&amp;lt;&quot;Courier: Current State: &quot;&amp;lt;&amp;lt;_stateToStrCourier[_state]&amp;lt;&amp;lt; std::endl;
#endif
  mySleep(500); /* Do some useful work here */

  _state++;
  if (_state == Complete)
   return 1;
  return 0;
 }
private:
 enum States
 {
  Received, VerifyReachbility, AssignPerson, DispatchPackage, GetDeliveryConfirmation, Complete
 };
 int _state;
};
 
class Vendor
{
public:
 void submitRequestToVendor()
 {
  _state = 0;
 }
 bool checkStatus()
 {
#ifdef DEBUG
  std::cout&amp;lt;&amp;lt;&quot;Vendor: Current State: &quot;&amp;lt;&amp;lt;_stateToStrVendor[_state]&amp;lt;&amp;lt; std::endl;
#endif
  mySleep(500); /* Do some useful work here */

  _state++;
  if (_state == Complete)
   return 1;
  return 0;
 }
private:
 enum States
 {
  Received, VerifyInventory, GetItemFromWareHouse, PackItem, ContactCourier, Complete
 };
 int _state;
 
};
 
class OrderingTeam
{
public:
 void submitRequestToOrderTeam()
 {
  _state = 0;
 }
 bool checkStatus()
 {
#ifdef DEBUG
  std::cout&amp;lt;&amp;lt;&quot;OrderingTeam: Current State: &quot;&amp;lt;&amp;lt;_stateToStrOrderTeam[_state]&amp;lt;&amp;lt; std::endl;
#endif
  mySleep(500); /* Do some useful work here */ 
  _state++;
  if (_state == Complete)
   return 1;
  return 0;
 }
private:
 enum States
 {
  Received, VerifyPayment, ContactVendor, Complete
 };
 int _state;
};
 
class OnlineShoppingFacade
{
public:
 OnlineShoppingFacade()
 {
  _count = 0;
 }
 void submitRequest()
 {
  _state = 0;
 }
 bool checkStatus()
 {
  /* Item request has just been received */
  switch(_state)
  {
  case Received:
   _state++;
   /* Forward the job request to the ordering team */
   _order.submitRequestToOrderTeam();
   std::cout &amp;lt;&amp;lt; &quot;submitted to Order Team - &quot; &amp;lt;&amp;lt; _count &amp;lt;&amp;lt;
    &quot; followups till now&quot; &amp;lt;&amp;lt; std::endl;
   break;
  case SubmittedToOrderTeam:
   /* If order team has completed verification, 
   place the request with vendor */
   if (_order.checkStatus())
   {
    _state++;
    _vendor.submitRequestToVendor();
    std::cout &amp;lt;&amp;lt; &quot;submitted to Vendor - &quot; &amp;lt;&amp;lt; _count &amp;lt;&amp;lt;
     &quot; followups till now&quot; &amp;lt;&amp;lt; std::endl;
   }
   break;
  case SubmittedToVendor:
   /* If vendor has packed the item, forward it to courier */
   if (_vendor.checkStatus())
   {
    _state++;
    _courier.submitRequestToCourier();
    std::cout &amp;lt;&amp;lt; &quot;submitted to Courier - &quot; &amp;lt;&amp;lt; _count &amp;lt;&amp;lt;
     &quot; followups till now&quot; &amp;lt;&amp;lt; std::endl;
   }
   break;
  case SubmittedToCourier:
   /* If package is delivered, order is complete */
   if (_courier.checkStatus())
    return 1;
  default:
   break;
  }
 
  _count++;
 
  /* The order is not complete */
  return 0;
 }
 int numFUPs()
 
 {
  return _count;
 }
private:
 enum States
 {
  Received, SubmittedToOrderTeam, SubmittedToVendor, SubmittedToCourier
 };
 
 int _state;
 int _count;
 
 OrderingTeam _order;
 Vendor _vendor;
 Courier _courier;
};
 
int main()
{
 OnlineShoppingFacade onlinereq;
 
 onlinereq.submitRequest();
 
 /* Keep checking until order is complete */
 while (!onlinereq.checkStatus());
 
 std::cout &amp;lt;&amp;lt; &quot;Order completed after &quot; &amp;lt;&amp;lt; onlinereq.numFUPs() &amp;lt;&amp;lt; 
  &quot; followups&quot; &amp;lt;&amp;lt; std::endl;
}

&lt;/code&gt;
&lt;/pre&gt;

&lt;/div&gt;
&lt;/div&gt;</description><link>http://simplestcodings.blogspot.com/2014/10/facade-design-pattern-in-cpp.html</link><author>noreply@blogger.com (Varun)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi1JrJeJkRpdSUZbykBJbaeyiPhZDJu7cRF4Feej_hIkRzpbQzuM71_Z7tGzUO9BW9j2SIyu1657UgZGaq94Eu6_MrA6x9RStN0EZpjC_5AA3u88bltAejru3WgFo8zo5taMUKsTlvXqcM/s72-c/facade.png" height="72" width="72"/><thr:total>6</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-3459284654925679524.post-4469157678134993840</guid><pubDate>Sat, 18 Oct 2014 17:07:00 +0000</pubDate><atom:updated>2023-12-21T00:39:36.532+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">gSOAP</category><category domain="http://www.blogger.com/atom/ns#">SOAP</category><category domain="http://www.blogger.com/atom/ns#">Web Service</category><category domain="http://www.blogger.com/atom/ns#">Xerces</category><category domain="http://www.blogger.com/atom/ns#">XML</category><title>Create a SOAP web service client in C++</title><description>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;h1&gt;What is SOAP?&lt;/h1&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjox1D6j-O6zV_8eUuRlKiJSNV6FtUYaZRbYraOrsLk4LduY-KX2Wjq1gzSI-eSVegmzaCt4HL_gNJFSGJg9irUOT9Gr5ol7qhqumbImE9HSoKDpS8AI2umxojjmf6Z6S-TSeP6iCkwYTHArz0UB_HbIzU7-_SNfQdyNVnXL_ta8N1fI4u74E1jiTh7lzs/s1024/soap_black.jpeg&quot; style=&quot;display: block; padding: 1em 0px; text-align: center;&quot;&gt;&lt;img alt=&quot;&quot; border=&quot;0&quot; data-original-height=&quot;1024&quot; data-original-width=&quot;1024&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjox1D6j-O6zV_8eUuRlKiJSNV6FtUYaZRbYraOrsLk4LduY-KX2Wjq1gzSI-eSVegmzaCt4HL_gNJFSGJg9irUOT9Gr5ol7qhqumbImE9HSoKDpS8AI2umxojjmf6Z6S-TSeP6iCkwYTHArz0UB_HbIzU7-_SNfQdyNVnXL_ta8N1fI4u74E1jiTh7lzs/s320/soap_black.jpeg&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;&lt;/div&gt;  
SOAP(Simple Object Access Protocol) is a great way to exchange information over the network. Normally it is used with application protocols like HTTP, SMTP etc. The envelope containing the information is XML based.&lt;br /&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
It provides the basic messaging infrastructure for web services.&amp;nbsp;&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
An example SOAP request looks like :&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;/div&gt;

&lt;pre class=&quot;prettyprint&quot;&gt; &lt;code class=&quot;language-xml&quot;&gt;
&amp;lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&amp;gt;
&amp;lt;soapenv:Envelope
        xmlns:soapenv=&quot;http://schemas.xmlsoap.org/soap/envelope/&quot;
        xmlns:xsd=&quot;http://www.w3.org/2001/XMLSchema&quot;
        xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;&amp;gt;
  &amp;lt;soapenv:Header&amp;gt;
    &amp;lt;ns1:RequestHeader
         soapenv:actor=&quot;http://schemas.xmlsoap.org/soap/actor/next&quot;
         soapenv:mustUnderstand=&quot;0&quot;
         xmlns:ns1=&quot;https://www.google.com/apis/ads/publisher/v201403&quot;&amp;gt;
      &amp;lt;ns1:networkCode&amp;gt;123456&amp;lt;/ns1:networkCode&amp;gt;
      &amp;lt;ns1:applicationName&amp;gt;DfpApi-Java-2.1.0-dfp_test&amp;lt;/ns1:applicationName&amp;gt;
    &amp;lt;/ns1:RequestHeader&amp;gt;
  &amp;lt;/soapenv:Header&amp;gt;
  &amp;lt;soapenv:Body&amp;gt;
    &amp;lt;getAdUnitsByStatement xmlns=&quot;https://www.google.com/apis/ads/publisher/v201403&quot;&amp;gt;
      &amp;lt;filterStatement&amp;gt;
        &amp;lt;query&amp;gt;WHERE parentId IS NULL LIMIT 500&amp;lt;/query&amp;gt;
      &amp;lt;/filterStatement&amp;gt;
    &amp;lt;/getAdUnitsByStatement&amp;gt;
  &amp;lt;/soapenv:Body&amp;gt;
&amp;lt;/soapenv:Envelope&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

The corresponding response would look like :
&lt;pre class=&quot;prettyprint&quot;&gt; &lt;code class=&quot;language-xml&quot;&gt;
&amp;lt;soap:Envelope xmlns:soap=&quot;http://schemas.xmlsoap.org/soap/envelope/&quot;&amp;gt;
  &amp;lt;soap:Header&amp;gt;
    &amp;lt;ResponseHeader xmlns=&quot;https://www.google.com/apis/ads/publisher/v201403&quot;&amp;gt;
      &amp;lt;requestId&amp;gt;xxxxxxxxxxxxxxxxxxxx&amp;lt;/requestId&amp;gt;
      &amp;lt;responseTime&amp;gt;1063&amp;lt;/responseTime&amp;gt;
    &amp;lt;/ResponseHeader&amp;gt;
  &amp;lt;/soap:Header&amp;gt;
  &amp;lt;soap:Body&amp;gt;
    &amp;lt;getAdUnitsByStatementResponse xmlns=&quot;https://www.google.com/apis/ads/publisher/v201403&quot;&amp;gt;
      &amp;lt;rval&amp;gt;
        &amp;lt;totalResultSetSize&amp;gt;1&amp;lt;/totalResultSetSize&amp;gt;
        &amp;lt;startIndex&amp;gt;0&amp;lt;/startIndex&amp;gt;
        &amp;lt;results&amp;gt;
          &amp;lt;id&amp;gt;2372&amp;lt;/id&amp;gt;
          &amp;lt;name&amp;gt;RootAdUnit&amp;lt;/name&amp;gt;
          &amp;lt;description&amp;gt;&amp;lt;/description&amp;gt;
          &amp;lt;targetWindow&amp;gt;TOP&amp;lt;/targetWindow&amp;gt;
          &amp;lt;status&amp;gt;ACTIVE&amp;lt;/status&amp;gt;
          &amp;lt;adUnitCode&amp;gt;1002372&amp;lt;/adUnitCode&amp;gt;
          &amp;lt;inheritedAdSenseSettings&amp;gt;
            &amp;lt;value&amp;gt;
              &amp;lt;adSenseEnabled&amp;gt;true&amp;lt;/adSenseEnabled&amp;gt;
              &amp;lt;borderColor&amp;gt;FFFFFF&amp;lt;/borderColor&amp;gt;
              &amp;lt;titleColor&amp;gt;0000FF&amp;lt;/titleColor&amp;gt;
              &amp;lt;backgroundColor&amp;gt;FFFFFF&amp;lt;/backgroundColor&amp;gt;
              &amp;lt;textColor&amp;gt;000000&amp;lt;/textColor&amp;gt;
              &amp;lt;urlColor&amp;gt;008000&amp;lt;/urlColor&amp;gt;
              &amp;lt;adType&amp;gt;TEXT_AND_IMAGE&amp;lt;/adType&amp;gt;
              &amp;lt;borderStyle&amp;gt;DEFAULT&amp;lt;/borderStyle&amp;gt;
              &amp;lt;fontFamily&amp;gt;DEFAULT&amp;lt;/fontFamily&amp;gt;
              &amp;lt;fontSize&amp;gt;DEFAULT&amp;lt;/fontSize&amp;gt;
            &amp;lt;/value&amp;gt;
          &amp;lt;/inheritedAdSenseSettings&amp;gt;
        &amp;lt;/results&amp;gt;
      &amp;lt;/rval&amp;gt;
    &amp;lt;/getAdUnitsByStatementResponse&amp;gt;
  &amp;lt;/soap:Body&amp;gt;
&amp;lt;/soap:Envelope&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

  
&lt;span style=&quot;font-size: xx-small;&quot;&gt;Courtesy :&amp;nbsp;&lt;a href=&quot;https://developers.google.com/doubleclick-publishers/docs/soap_xml&quot;&gt;https://developers.google.com/doubleclick-publishers/docs/soap_xml&lt;/a&gt;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
The above is an example of Google&#39;s web service which provides Ad Units to the requester based on some filters.&lt;br /&gt;
&lt;br /&gt;
Web Services provide an easy platform independent way to exchange information over the network.&lt;br /&gt;
The following picture shows the basic flow on how the Service Provider caters the request of the consumer.&lt;br /&gt;
&lt;br /&gt;
&lt;table align=&quot;center&quot; cellpadding=&quot;0&quot; cellspacing=&quot;0&quot; class=&quot;tr-caption-container&quot; style=&quot;margin-left: auto; margin-right: auto; text-align: center;&quot;&gt;&lt;tbody&gt;
&lt;tr&gt;&lt;td style=&quot;text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj2jTrSKGAUSHZgCuq6Y2aT5Qb4oS3FHOuzYrDsVIslg-zwcTZ-cYP9KoRdvBknvNFYJV8qvnJ6z5AX19oiIkajXIEkz2SH730jKlmgTvmu6OVVKtgiWMEuri9cyLpLz7plVLOG9WUv3C4/s1600/soap_messages.jpg&quot; style=&quot;margin-left: auto; margin-right: auto;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;260&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj2jTrSKGAUSHZgCuq6Y2aT5Qb4oS3FHOuzYrDsVIslg-zwcTZ-cYP9KoRdvBknvNFYJV8qvnJ6z5AX19oiIkajXIEkz2SH730jKlmgTvmu6OVVKtgiWMEuri9cyLpLz7plVLOG9WUv3C4/s1600/soap_messages.jpg&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td class=&quot;tr-caption&quot; style=&quot;text-align: center;&quot;&gt;&lt;span style=&quot;font-size: xx-small;&quot;&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;Source: &lt;a href=&quot;http://www.service-architecture.com/&quot;&gt;http://www.service-architecture.com&lt;/a&gt;&lt;/span&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
Following is an implementation of a SOAP client in C++ which calls the Web Service to get the stock quotes based on a symbol(company ticker).&lt;br /&gt;
&lt;br /&gt;
The example uses gSoap library for SOAP encoding/decoding and Xerces library to extract the data from the SOAP response (XML).&lt;br /&gt;
&lt;br /&gt;
I have used the web service URL&amp;nbsp;&lt;a href=&quot;http://www.webservicex.net/stockquote.asmx?WSDL&quot;&gt;http://www.webservicex.net/stockquote.asmx?WSDL&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;&lt;u&gt;Resources:&lt;/u&gt;&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;ol&gt;
&lt;li&gt;gSOAP library (2.8.18)&amp;nbsp;&lt;a href=&quot;http://sourceforge.net/projects/gsoap2/files/&quot;&gt;http://sourceforge.net/projects/gsoap2/files/&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Xerces library (3.1.1)&amp;nbsp;&lt;a href=&quot;http://xerces.apache.org/mirrors.cgi#binary&quot;&gt;http://xerces.apache.org/mirrors.cgi#binary&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;div&gt;
&lt;b&gt;&lt;u&gt;Setup for Visual Studio 2005:&lt;/u&gt;&lt;/b&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;/div&gt;
&lt;ol style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;Unzip gSOAP library at any location (Lets say C:\tools , so the location will be &lt;b&gt;C:\gsoap-2.8&lt;/b&gt;)&lt;/li&gt;
&lt;li&gt;Download only the binary distribution of xerces &lt;b&gt;&lt;span style=&quot;color: blue;&quot;&gt;&lt;a href=&quot;http://mirror.cc.columbia.edu/pub/software/apache//xerces/c/3/binaries/xerces-c-3.1.1-x86-windows-vc-8.0.zip&quot; target=&quot;_blank&quot;&gt;xerces-c-3.1.1-x86-windows-vc-8.0.zip&lt;/a&gt;&lt;/span&gt;&lt;/b&gt;&lt;/li&gt;
&lt;li&gt;Unzip the zip file at C:\ &amp;nbsp;so that location becomes &lt;b&gt;C:\xerces-c-3.1.1-x86-windows-vc-8.0&lt;/b&gt;&lt;/li&gt;
&lt;li&gt;Create an empty Win32 Console Application project.&lt;/li&gt;
&lt;li&gt;Add theses paths to the Additional Include Directories : &lt;br /&gt;&quot;C:\xerces-c-3.1.1-x86-windows-vc-8.0\include&quot;;&quot;C:\gsoap-2.8\gsoap\&quot;;&quot;C:\gsoap-2.8\gsoap\import&quot;&lt;br /&gt;&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi_9rs4g8gDk7hxkwHXHiugkrVMkz4iFIzuMR4fIrI8BGNVoJk5qF8ZFeXWwbD1dJH3RT5Xu9Mk_e5dAzCRGvtGbvYzgWm68AlWJ2UYUYHkzt3WW01kMUFznp6Xkemscuj2BaKPB8LBqyw/s1600/include.png&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;291&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi_9rs4g8gDk7hxkwHXHiugkrVMkz4iFIzuMR4fIrI8BGNVoJk5qF8ZFeXWwbD1dJH3RT5Xu9Mk_e5dAzCRGvtGbvYzgWm68AlWJ2UYUYHkzt3WW01kMUFznp6Xkemscuj2BaKPB8LBqyw/s1600/include.png&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;/li&gt;
&lt;li&gt;Add these paths to Additional Library Directories :&lt;br /&gt;&quot;C:\xerces-c-3.1.1-x86-windows-vc-8.0\lib&quot;&lt;br /&gt;&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjGPaS7ISn04z8rAn1CNaJX7SEBmnqvZY2iBgOpKagRImINL3807A0k6zIlcwLI_-JEMsdvQhr8WsRjoPNQ4R5Sed3GVgZZetu_3Stqf0fsvK0fzLMZkb03hCaq5JZ106P93rQ0zmesWzY/s1600/lib.png&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;313&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjGPaS7ISn04z8rAn1CNaJX7SEBmnqvZY2iBgOpKagRImINL3807A0k6zIlcwLI_-JEMsdvQhr8WsRjoPNQ4R5Sed3GVgZZetu_3Stqf0fsvK0fzLMZkb03hCaq5JZ106P93rQ0zmesWzY/s1600/lib.png&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;/li&gt;
&lt;li&gt;Add these libs to the dependency list:&lt;br /&gt;&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi0qPzjnOeo2lozlcFziUafgdU0cUoinvxfycZg5fFC7FGM8Qmux6raCwnKyIvy-McpET04hCmCmKXYPTnPHKwJIWQRM8kxdzqF-phMBbBiCQkdpTxshoiCnmmILYnG40sEmWdlI-5uqoE/s1600/lib1.png&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;300&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi0qPzjnOeo2lozlcFziUafgdU0cUoinvxfycZg5fFC7FGM8Qmux6raCwnKyIvy-McpET04hCmCmKXYPTnPHKwJIWQRM8kxdzqF-phMBbBiCQkdpTxshoiCnmmILYnG40sEmWdlI-5uqoE/s1600/lib1.png&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div style=&quot;text-align: left;&quot;&gt;
&lt;br /&gt;
Notice that since we are using a Debug configuration here, we added &lt;b&gt;xerces-c_3D.lib. &lt;/b&gt;For Release configuration, use&amp;nbsp;&lt;b&gt;xerces-c_3.lib&lt;/b&gt;&lt;/div&gt;
&lt;/li&gt;
&lt;li&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
&lt;/div&gt;
Add this location to your environment Path variable&amp;nbsp;&lt;b style=&quot;font-size: small;&quot;&gt;C:\xerces-c-3.1.1-x86-windows-vc-8.0\bin &lt;/b&gt;or copy the xerces dlls (&lt;b&gt;xerces-c_3_1.dll&lt;/b&gt; and &lt;b&gt;xerces-c_3_1D.dll&lt;/b&gt;) into the output path of the project(i.e. same path where the exe of the project will be created). These will be present at the location&amp;nbsp;&lt;b style=&quot;font-size: small;&quot;&gt;C:\xerces-c-3.1.1-x86-windows-vc-8.0\bin&lt;/b&gt;&lt;/li&gt;
&lt;li&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
Open a command prompt and go to gSOAP win32 bin directory and run following commands :&lt;/div&gt;
&lt;span style=&quot;font-family: Courier New, Courier, monospace; font-weight: bold;&quot;&gt;&lt;br /&gt;wsdl2h.exe -o quote.h http://www.webservicex.net/stockquote.asmx?WSDL&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;font-family: inherit;&quot;&gt;This will generate quote.h which contains class definitions for the web service.&lt;/span&gt;&lt;br /&gt;&lt;b&gt;&lt;span style=&quot;font-family: Courier New, Courier, monospace;&quot;&gt;soapcpp2.exe /IC:\tools\gsoap_2.8.18\gsoap-2.8\gsoap\import quote.h&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;This generates following files :&lt;br /&gt;&lt;br /&gt;StockQuoteSoap.GetQuote.req.xml&lt;br /&gt;StockQuoteSoap.GetQuote.res.xml&lt;br /&gt;StockQuoteSoap.nsmap&lt;br /&gt;soapC.cpp&lt;br /&gt;soapClient.cpp&lt;br /&gt;soapClientLib.cpp&lt;br /&gt;soapH.h&lt;br /&gt;soapServer.cpp&lt;br /&gt;soapServerLib.cpp&lt;br /&gt;soapStub.h&lt;/li&gt;
&lt;li&gt;&lt;span style=&quot;font-family: inherit;&quot;&gt;Now add these generated files to the Visual Studio project created earlier :&lt;br /&gt;&lt;b&gt;soapH.h ,&amp;nbsp;&lt;/b&gt;&lt;/span&gt;&lt;b&gt;soapC.cpp,&amp;nbsp;soapClient.cpp,&amp;nbsp;soapStub.h,&amp;nbsp;quote.h&lt;/b&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;font-family: inherit;&quot;&gt;Also these add two additional files from&amp;nbsp;&lt;/span&gt;&lt;span style=&quot;font-family: inherit;&quot;&gt;&lt;b&gt;C:\tools\gsoap_2.8.18\gsoap-2.8\gsoap &lt;/b&gt;to your project:&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;font-family: inherit;&quot;&gt;&lt;b&gt;stdsoap2.cpp,&amp;nbsp;stdsoap2.h&lt;/b&gt;&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;Now its time to create some files on our own :). &amp;nbsp;Create these files in the project and copy the contents from the code below :&lt;br /&gt;&lt;br /&gt;&lt;b&gt;quote.cpp, parser.hpp, stock.hpp&lt;/b&gt;&lt;/li&gt;
&lt;h1&gt;SOAP Web Service client implementation(c++)&lt;/h1&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;&lt;code class=&quot;language-cpp&quot;&gt;
//quote.cpp
#include &quot;soapH.h&quot;    // include the generated proxy
#include &amp;lt;xercesc/sax/HandlerBase.hpp&amp;gt;
#include &amp;lt;xercesc/util/XMLString.hpp&amp;gt;
#include &amp;lt;xercesc/framework/MemBufInputSource.hpp&amp;gt;
#include &amp;lt;xercesc/util/OutOfMemoryException.hpp&amp;gt;
#include &amp;lt;xercesc/dom/DOM.hpp&amp;gt;
#include &amp;lt;xercesc/dom/DOMDocument.hpp&amp;gt;
#include &amp;lt;xercesc/dom/DOMDocumentType.hpp&amp;gt;
#include &amp;lt;xercesc/dom/DOMElement.hpp&amp;gt;
#include &amp;lt;xercesc/dom/DOMImplementation.hpp&amp;gt;
#include &amp;lt;xercesc/dom/DOMImplementationLS.hpp&amp;gt;
#include &amp;lt;xercesc/dom/DOMNodeIterator.hpp&amp;gt;
#include &amp;lt;xercesc/dom/DOMNodeList.hpp&amp;gt;
#include &amp;lt;xercesc/dom/DOMText.hpp&amp;gt;
#include &amp;lt;xercesc/parsers/XercesDOMParser.hpp&amp;gt;
#include &amp;lt;xercesc/util/XMLUni.hpp&amp;gt;
#include &quot;parser.hpp&quot;

XERCES_CPP_NAMESPACE_USE

GetXml::GetXml()
{
 try
 {
  XMLPlatformUtils::Initialize();  // Initialize Xerces infrastructure
 }
 catch( XMLException&amp;amp; e )
 {
  char* message = XMLString::transcode( e.getMessage() );
  std::cout &amp;lt;&amp;lt; &quot;XML toolkit initialization error: &quot; &amp;lt;&amp;lt; message &amp;lt;&amp;lt; std::endl;
  XMLString::release( &amp;amp;message );
 }

 // Tags and attributes used in XML file.
 // Can&#39;t call transcode till after Xerces Initialize()
 TAG_root  = XMLString::transcode(&quot;StockQuotes&quot;);
 TAG_Stock = XMLString::transcode(&quot;Stock&quot;);
 TAG_Symbol = XMLString::transcode(&quot;Symbol&quot;);
 TAG_Last = XMLString::transcode(&quot;Last&quot;);
 TAG_Date = XMLString::transcode(&quot;Date&quot;);
 TAG_Time = XMLString::transcode(&quot;Time&quot;);
 TAG_Change = XMLString::transcode(&quot;Change&quot;);
 TAG_Open = XMLString::transcode(&quot;Open&quot;);
 TAG_High = XMLString::transcode(&quot;High&quot;);
 TAG_Low = XMLString::transcode(&quot;Low&quot;);
 TAG_Volume = XMLString::transcode(&quot;Volume&quot;);
 TAG_MktCap = XMLString::transcode(&quot;MktCap&quot;);
 TAG_PrevClose = XMLString::transcode(&quot;PreviousClose&quot;);
 TAG_PercentChange = XMLString::transcode(&quot;PercentageChange&quot;);
 TAG_AnnRange = XMLString::transcode(&quot;AnnRange&quot;);
 TAG_Earns = XMLString::transcode(&quot;Earns&quot;);
 TAG_PE = XMLString::transcode(&quot;P-E&quot;);
 TAG_Name = XMLString::transcode(&quot;Name&quot;);
 
 m_XmlParser = new XercesDOMParser;
 m_Stock = new Stock;
}

GetXml::~GetXml()
{
 // Free memory
 delete m_XmlParser;
 delete m_Stock;

 try
 {
  XMLString::release( &amp;amp;TAG_root );
 }
 catch( ... )
 {
  std::cout &amp;lt;&amp;lt; &quot;Unknown exception encountered in Destructor&quot; &amp;lt;&amp;lt; std::endl;
 }

 // Terminate Xerces
 try
 {
  XMLPlatformUtils::Terminate();  // Terminate after release of memory
 }
 catch( xercesc::XMLException&amp;amp; e )
 {
  char* message = xercesc::XMLString::transcode( e.getMessage() );

  std::cout &amp;lt;&amp;lt; &quot;XML toolkit teardown error: &quot; &amp;lt;&amp;lt; message &amp;lt;&amp;lt; std::endl;
  XMLString::release( &amp;amp;message );
 }
}

void GetXml::readXml(std::string&amp;amp; xmlStr)
throw( std::runtime_error )
{
 // Configure DOM parser.
 m_XmlParser-&amp;gt;setValidationScheme( XercesDOMParser::Val_Never );
 m_XmlParser-&amp;gt;setDoNamespaces( false );
 m_XmlParser-&amp;gt;setDoSchema( false );
 m_XmlParser-&amp;gt;setLoadExternalDTD( false );

 try
 {
  xercesc_3_1::MemBufInputSource xmlBuf((const XMLByte*)xmlStr.c_str(), xmlStr.size(),
   &quot;xmlBuf (in memory)&quot;);
  m_XmlParser-&amp;gt;parse( xmlBuf );

  xercesc_3_1::DOMDocument* xmlDoc = m_XmlParser-&amp;gt;getDocument();

  DOMElement* elementRoot = xmlDoc-&amp;gt;getDocumentElement();
  if( !elementRoot ) throw(std::runtime_error( &quot;Empty XML document&quot; ));

  DOMNodeList*      children = elementRoot-&amp;gt;getChildNodes();
  const  XMLSize_t nodeCount = children-&amp;gt;getLength();

  // For all nodes, children of &quot;StockQuotes&quot; in the XML tree.

  for( XMLSize_t xx = 0; xx &amp;lt; nodeCount; ++xx )
  {
   DOMNode* currentNode = children-&amp;gt;item(xx);
   if( currentNode-&amp;gt;getNodeType() &amp;amp;&amp;amp;  // true is not NULL
    currentNode-&amp;gt;getNodeType() == DOMNode::ELEMENT_NODE ) // is element 
   {
    // Found node which is an Element. Re-cast node as element
    DOMElement* currentElement
     = dynamic_cast&amp;lt; xercesc::DOMElement* &amp;gt;( currentNode );
    if( XMLString::equals(currentElement-&amp;gt;getTagName(), TAG_Stock))
    {
     DOMNodeList*      children1 = currentElement-&amp;gt;getChildNodes();
     const  XMLSize_t nodeCount1 = children1-&amp;gt;getLength();
     for( XMLSize_t yy = 0; yy &amp;lt; nodeCount1; ++yy )
     {
      DOMNode* currentNode1 = children1-&amp;gt;item(yy);
      if( currentNode1-&amp;gt;getNodeType() &amp;amp;&amp;amp;  // true is not NULL
       currentNode1-&amp;gt;getNodeType() == DOMNode::ELEMENT_NODE ) // is element 
      {
       // Found node which is an Element. Re-cast node as element
       DOMElement* currentElement1
        = dynamic_cast&amp;lt; xercesc::DOMElement* &amp;gt;( currentNode1 );
       std::cout&amp;lt;&amp;lt;XMLString::transcode(currentElement1-&amp;gt;getTagName())&amp;lt;&amp;lt;&quot;: &quot;
        &amp;lt;&amp;lt;XMLString::transcode(currentElement1-&amp;gt;getTextContent())&amp;lt;&amp;lt;std::endl;

       std::string sym(XMLString::transcode(currentElement1-&amp;gt;getTextContent()));

       if(XMLString::equals(currentElement1-&amp;gt;getTagName(), TAG_Symbol))
       {
        m_Stock-&amp;gt;SetSymbol(sym);
       }
       else if(XMLString::equals(currentElement1-&amp;gt;getTagName(), TAG_Last))
       {
        m_Stock-&amp;gt;SetLast(sym);
       }
       else if(XMLString::equals(currentElement1-&amp;gt;getTagName(), TAG_Date))
       {
        m_Stock-&amp;gt;SetDate(sym);
       }
       else if(XMLString::equals(currentElement1-&amp;gt;getTagName(), TAG_Time))
       {
        m_Stock-&amp;gt;SetTime(sym);

       }
       else if(XMLString::equals(currentElement1-&amp;gt;getTagName(), TAG_Change))
       {
        m_Stock-&amp;gt;SetChange(sym);

       }
       else if(XMLString::equals(currentElement1-&amp;gt;getTagName(), TAG_Open))
       {
        m_Stock-&amp;gt;SetOpen(sym);

       }
       else if(XMLString::equals(currentElement1-&amp;gt;getTagName(), TAG_High))
       {
        m_Stock-&amp;gt;SetHigh(sym);

       }
       else if(XMLString::equals(currentElement1-&amp;gt;getTagName(), TAG_Low))
       {
        m_Stock-&amp;gt;SetLow(sym);

       }
       else if(XMLString::equals(currentElement1-&amp;gt;getTagName(), TAG_Volume))
       {
        m_Stock-&amp;gt;SetVolume(sym);

       }
       else if(XMLString::equals(currentElement1-&amp;gt;getTagName(), TAG_MktCap))
       {
        m_Stock-&amp;gt;SetMktCap(sym);

       }
       else if(XMLString::equals(currentElement1-&amp;gt;getTagName(), TAG_PrevClose))
       {
        m_Stock-&amp;gt;SetPrevClose(sym);

       }
       else if(XMLString::equals(currentElement1-&amp;gt;getTagName(), TAG_PercentChange))
       {
        m_Stock-&amp;gt;SetPercentChange(sym);

       }
       else if(XMLString::equals(currentElement1-&amp;gt;getTagName(), TAG_AnnRange))
       {
        m_Stock-&amp;gt;SetAnnRange(sym);

       }
       else if(XMLString::equals(currentElement1-&amp;gt;getTagName(), TAG_Earns))
       {
        m_Stock-&amp;gt;SetEarns(sym);

       }
       else if(XMLString::equals(currentElement1-&amp;gt;getTagName(), TAG_PE))
       {
        m_Stock-&amp;gt;SetPE(sym);

       }
       else if(XMLString::equals(currentElement1-&amp;gt;getTagName(), TAG_Name))
       {
        m_Stock-&amp;gt;SetName(sym);
       }
      }
     }
    }
   }
  }

  std::cout&amp;lt;&amp;lt;m_Stock-&amp;gt;ToString();
 }
 catch( xercesc::XMLException&amp;amp; e )
 {
  char* message = xercesc::XMLString::transcode( e.getMessage() );
  std::ostringstream errBuf;
  errBuf &amp;lt;&amp;lt; &quot;Error parsing file: &quot; &amp;lt;&amp;lt; message &amp;lt;&amp;lt; std::flush;
  XMLString::release( &amp;amp;message );
 }
}

int main(int argc, char** argv){
 struct soap *soap = soap_new(); 
 struct _ns1__GetQuote sym;
 struct _ns1__GetQuoteResponse quote;
 GetXml xml;
 std::string response=&quot;&quot;;
 std::string str(argv[1]);
 sym.symbol = &amp;amp;str;

 soap_init(soap);

 //Call the web service
 if (soap_call___ns1__GetQuote(soap, NULL, NULL, &amp;amp;sym, quote) == SOAP_OK) {
  //std::cout&amp;lt;&amp;lt;&quot;Symbol: &quot;&amp;lt;&amp;lt;*(sym.symbol)&amp;lt;&amp;lt;std::endl&amp;lt;&amp;lt;&quot; Quote: &quot;&amp;lt;&amp;lt;*(quote.GetQuoteResult)&amp;lt;&amp;lt;std::endl;
  response = *(quote.GetQuoteResult);
  free (quote.GetQuoteResult);
 }
 else {
  std::cout&amp;lt;&amp;lt;&quot;Error in execution of GetQuote:: &quot;&amp;lt;&amp;lt;soap-&amp;gt;buf&amp;lt;&amp;lt;std::endl;
  return(0);
 }

 //Parse the SOAP response 
 xml.readXml(response);
 return 0;
}

// Copied from StockQuoteSoap.nsmap file
SOAP_NMAC struct Namespace namespaces[] =
{
 {&quot;SOAP-ENV&quot;, &quot;http://www.w3.org/2003/05/soap-envelope&quot;, &quot;http://schemas.xmlsoap.org/soap/envelope/&quot;, NULL},
 {&quot;SOAP-ENC&quot;, &quot;http://www.w3.org/2003/05/soap-encoding&quot;, &quot;http://schemas.xmlsoap.org/soap/encoding/&quot;, NULL},
 {&quot;xsi&quot;, &quot;http://www.w3.org/2001/XMLSchema-instance&quot;, &quot;http://www.w3.org/*/XMLSchema-instance&quot;, NULL},
 {&quot;xsd&quot;, &quot;http://www.w3.org/2001/XMLSchema&quot;, &quot;http://www.w3.org/*/XMLSchema&quot;, NULL},
 {&quot;ns1&quot;, &quot;http://www.webserviceX.NET/&quot;, NULL, NULL},
 {NULL, NULL, NULL, NULL}
};
&lt;/code&gt;
&lt;/pre&gt;
&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;&lt;code class=&quot;language-cpp&quot;&gt;
//stock.hpp
#include &amp;lt;sstream&amp;gt;
class Stock
{
 std::string symbol_;
 std::string last_;
 std::string date_;
 std::string time_;
 std::string change_;
 std::string open_;
 std::string high_;
 std::string low_;
 std::string volume_;
 std::string mktcap_;
 std::string previousclose_;
 std::string percentagechange_;
 std::string annrange_;
 std::string earns_;
 std::string p_e_;
 std::string name_;

public:
 Stock() {}
 Stock(std::string symbol) {symbol_ = symbol;}

 void SetSymbol(std::string symbol) {symbol_ = symbol;}
 void SetLast(std::string last) {last_ = last;}
 void SetDate(std::string date) {date_ = date;}
 void SetTime(std::string time) {time_ = time;}
 void SetChange(std::string change) {change_ = change;}
 void SetOpen(std::string open) {open_ = open;}
 void SetHigh(std::string high) {high_ = high;}
 void SetLow(std::string low) {low_ = low;}
 void SetVolume(std::string volume) {volume_ = volume;}
 void SetMktCap(std::string mktcap) {mktcap_ = mktcap;}
 void SetPrevClose(std::string previousclose) {previousclose_ = previousclose;}
 void SetPercentChange(std::string percentagechange) {percentagechange_ = percentagechange;}
 void SetAnnRange(std::string annrange) {annrange_ = annrange;}
 void SetEarns(std::string earns) {earns_ = earns;}
 void SetPE(std::string p_e) {p_e_ = p_e;}
 void SetName(std::string name) {name_ = name;}

 //ToString function overridden to display in short format  
 std::string ToString() const
 {
  std::stringstream sstr;
  sstr &amp;lt;&amp;lt; &quot;\&#39;&quot; &amp;lt;&amp;lt; symbol_ &amp;lt;&amp;lt; &quot;\&#39; Open: &quot; &amp;lt;&amp;lt; open_
   &amp;lt;&amp;lt; &quot;, Last: &quot; &amp;lt;&amp;lt; last_;
  return sstr.str();
 }
};
&lt;/code&gt;
&lt;/pre&gt;
&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;&lt;code class=&quot;language-cpp&quot;&gt;
//parser.hpp
#include &quot;stock.hpp&quot;
class GetXml
{
public:
 GetXml();
 ~GetXml();

 //Function to read the XML string
 void readXml(std::string&amp;amp;) throw(std::runtime_error);


private:
 xercesc_3_1::XercesDOMParser *m_XmlParser; //DOM Parser pointer
 Stock *m_Stock;        //To save the returned data

 XMLCh* TAG_root;
 XMLCh* TAG_Stock;
 XMLCh* TAG_Symbol;
 XMLCh* TAG_Last;
 XMLCh* TAG_Date;
 XMLCh* TAG_Time;
 XMLCh* TAG_Change;
 XMLCh* TAG_Open;
 XMLCh* TAG_High;
 XMLCh* TAG_Low;
 XMLCh* TAG_Volume;
 XMLCh* TAG_MktCap;
 XMLCh* TAG_PrevClose;
 XMLCh* TAG_PercentChange;
 XMLCh* TAG_AnnRange;
 XMLCh* TAG_Earns;
 XMLCh* TAG_PE;
 XMLCh* TAG_Name;
};
&lt;/code&gt;
&lt;/pre&gt;

&lt;br /&gt;&lt;br /&gt;
&lt;li&gt;Now the project is ready to compile. Use F7 to compile the solution.&lt;/li&gt;
&lt;li&gt;After the binary is generated, run it like this :&lt;br /&gt;&amp;lt;binary-name&amp;gt;.exe&amp;lt;space&amp;gt;&amp;lt;Ticker-Name&amp;gt;&lt;br /&gt;&lt;br /&gt;e.g. If project name was soap&lt;br /&gt;soap.exe GOOG&lt;/li&gt;
&lt;li&gt;This program is specific to the Stock Quote web service provided by&amp;nbsp;&lt;a href=&quot;http://www.webservicex.net/stockquote.asmx?WSDL&quot;&gt;http://www.webservicex.net/&lt;/a&gt;&amp;nbsp;. This program can be modified to use any web service. Depending upon the expected SOAP response, the result can be parsed accordingly. Then following files will be modified :&lt;br /&gt;&lt;br /&gt;stock.hpp - Class which stores the data from SOAP response&lt;br /&gt;parser.hpp - Class which parses the XML result from SOAP response&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;</description><link>http://simplestcodings.blogspot.com/2014/10/create-soap-web-service-client-in-c.html</link><author>noreply@blogger.com (Varun)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjox1D6j-O6zV_8eUuRlKiJSNV6FtUYaZRbYraOrsLk4LduY-KX2Wjq1gzSI-eSVegmzaCt4HL_gNJFSGJg9irUOT9Gr5ol7qhqumbImE9HSoKDpS8AI2umxojjmf6Z6S-TSeP6iCkwYTHArz0UB_HbIzU7-_SNfQdyNVnXL_ta8N1fI4u74E1jiTh7lzs/s72-c/soap_black.jpeg" height="72" width="72"/><thr:total>3</thr:total><georss:featurename>Bengaluru, Karnataka, India</georss:featurename><georss:point>12.9715987 77.594562699999983</georss:point><georss:box>12.9715987 77.594562699999983 12.9715987 77.594562699999983</georss:box></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-3459284654925679524.post-4201802448737961412</guid><pubDate>Tue, 01 Apr 2014 20:21:00 +0000</pubDate><atom:updated>2023-12-21T00:18:35.910+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">Builder</category><category domain="http://www.blogger.com/atom/ns#">Builder Design Pattern</category><category domain="http://www.blogger.com/atom/ns#">Design Patterns</category><title>Builder Design Pattern Implementation in C++</title><description>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
Sometimes an application gets too complicated and developing it becomes a pain. These applications contain complex objects which are made up from other objects from different classes. Now these objects may vary. So there has to be a process of building the complex objects so that there is scope of building different products using the same process.&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
That is when a creational design pattern called &lt;b&gt;Builder&lt;/b&gt; comes into picture. It &lt;i&gt;separates the details of construction process from its representation&lt;/i&gt;.&amp;nbsp;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
Now what in the world that line means actually ?&amp;nbsp;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
It means that the construction process is made so generic, that multiple products can be produced using the same process. e.g. construction workers. Different type of buildings can be built using the same workers and same common set of process.&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
Here is a class diagram of the design pattern.&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;/div&gt;
&lt;table align=&quot;center&quot; cellpadding=&quot;0&quot; cellspacing=&quot;0&quot; class=&quot;tr-caption-container&quot; style=&quot;margin-left: auto; margin-right: auto; text-align: center;&quot;&gt;&lt;tbody&gt;
&lt;tr&gt;&lt;td style=&quot;text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgPCuiSYtUz_LTTio4VHshLte_KO0DWfRso2jryCVDwLdee0Oh913-33V4M84BoMHb9twa8IV1WT005VGeNtCwYJRCwOTJBWkIqc33AoY0rlYmwgEVLZ771k4yhcKO55oXy6j6dPgBJBzI/s1600/Builder.png&quot; style=&quot;margin-left: auto; margin-right: auto;&quot;&gt;&lt;img alt=&quot;Builder Design Pattern&quot; border=&quot;0&quot; height=&quot;252&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgPCuiSYtUz_LTTio4VHshLte_KO0DWfRso2jryCVDwLdee0Oh913-33V4M84BoMHb9twa8IV1WT005VGeNtCwYJRCwOTJBWkIqc33AoY0rlYmwgEVLZ771k4yhcKO55oXy6j6dPgBJBzI/s1600/Builder.png&quot; title=&quot;Builder Design Pattern&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td class=&quot;tr-caption&quot; style=&quot;text-align: center;&quot;&gt;Builder Design Pattern&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
There are 4 major components:&lt;br /&gt;
&lt;br /&gt;
&lt;ol style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;&lt;b&gt;Director&lt;/b&gt;: It constructs an object using the Builder interface.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Builder &lt;/b&gt;: It specifies an abstract interface to build parts of a product.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Concrete Classes &lt;/b&gt;: Implements builder interface.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Product &lt;/b&gt;: The complex object which is created at the end.&amp;nbsp;&lt;/li&gt;
&lt;/ol&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
Director object is created and Builder interface is used. It notifies the Builder to create each part of the product. Upon the request from Director, Builder adds parts to the product. Finally the product is returned by the Builder.&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
We have to take care of when to use the Builder Design Pattern. Few points come into mind :&lt;/div&gt;
&lt;div&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;When the object to be created is complex enough and can have multiple representations.&lt;/li&gt;
&lt;li&gt;When the construction process can be broken down into multiple steps&lt;/li&gt;
&lt;li&gt;When the process of creation of an object can be independent of the parts to be used.&lt;/li&gt;
&lt;li&gt;When different products can have a common abstract class.&lt;/li&gt;
&lt;/ul&gt;
&lt;div&gt;
Now lets create a builder design pattern using an example.&lt;br /&gt;
&lt;br /&gt;
&lt;table align=&quot;center&quot; cellpadding=&quot;0&quot; cellspacing=&quot;0&quot; class=&quot;tr-caption-container&quot; style=&quot;margin-left: auto; margin-right: auto; text-align: center;&quot;&gt;&lt;tbody&gt;
&lt;tr&gt;&lt;td style=&quot;text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgLQfwhE-O-vlIphK4tG6E1bK1At9P1cK2rpc7N6FYcgM9P6AoqxR7rGdpVM3DtxtGq2hVpt0DbOtOumZWfqiBGgy4leuW_UCR26VbiIiNVNeS8NLEADowZB4USRJgy2oUuJroXNugrrxg/s1600/BuilderExample.png&quot; style=&quot;margin-left: auto; margin-right: auto;&quot;&gt;&lt;img alt=&quot;Builder Design Pattern&quot; border=&quot;0&quot; height=&quot;482&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgLQfwhE-O-vlIphK4tG6E1bK1At9P1cK2rpc7N6FYcgM9P6AoqxR7rGdpVM3DtxtGq2hVpt0DbOtOumZWfqiBGgy4leuW_UCR26VbiIiNVNeS8NLEADowZB4USRJgy2oUuJroXNugrrxg/s1600/BuilderExample.png&quot; title=&quot;Builder Design Pattern&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td class=&quot;tr-caption&quot; style=&quot;text-align: center;&quot;&gt;Builder Example&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;br /&gt;
In this example we create house as product. Now the house created may be different as per requirement of different people. It can be a lavish house with lots of amenities and expensive stuff. On the other hand, it could be a normal house with normal stuff.&lt;br /&gt;
&lt;br /&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;The HouseBuilder class is the builder class which provides interface for creating the parts of the house.&lt;/li&gt;
&lt;li&gt;The House class is the final product that we want to build&lt;/li&gt;
&lt;li&gt;LavishHouse and NormalHouse are the concrete classes which implement the HouseBuilder interface.&lt;/li&gt;
&lt;li&gt;Contractor is the director which constructs the house using the HouseBuilder interface.&lt;/li&gt;
&lt;/ul&gt;
&lt;br /&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;
&lt;h1&gt;Builder Design Pattern Implementation(C++)&lt;/h1&gt;
&lt;pre class=&quot;prettyprint&quot;&gt; &lt;code class=&quot;language-cpp&quot;&gt;#include &amp;lt;iostream&amp;gt;

using namespace std;

/* Interface that will be returned as the product from builder */
class HousePlan{
public:
 virtual void setWindow(string window)=0;
 virtual void setDoor(string door)=0;
 virtual void setBathroom(string bathroom)=0;
 virtual void setKitchen(string kitchen)=0;
 virtual void setFloor(string floor)=0;
};

/* Concrete class for the HousePlan interface */
class House:public HousePlan{
private :
 string window, door, kitchen, bathroom, floor;

public:
 void setWindow(string window)
 {
  this-&amp;gt;window = window;
 }

 void setDoor(string door)
 {
  this-&amp;gt;door = door;
 }

 void setBathroom(string bathroom)
 {
  this-&amp;gt;bathroom = bathroom;
 }

 void setKitchen(string kitchen)
 {
  this-&amp;gt;kitchen = kitchen;
 }

 void setFloor(string floor)
 {
  this-&amp;gt;floor = floor;
 }
};

/* Builder Class */
class HouseBuilder
{
public:
 /* Abstract functions to build parts */
 virtual void buildWindow()=0;
 virtual void buildDoor()=0;
 virtual void buildKitchen()=0;
 virtual void buildBathroom()=0;
 virtual void buildFloor()=0;
 /* The product is returned by this function */
 virtual House* getHouse()=0;
};

/* Concrete class for the builder interface */
class LavishHouse:public HouseBuilder{
private:
 House *house;
public:
 LavishHouse()
 {
  house = new House();
 }

 void buildWindow()
 {
  house-&amp;gt;setWindow(&quot;French Window&quot;);
 }

 void buildDoor()
 {
  house-&amp;gt;setDoor(&quot;Wooden Door&quot;);
 }

 void buildBathroom()
 {
  house-&amp;gt;setBathroom(&quot;Modern Bathroom&quot;);
 }

 void buildKitchen()
 {
  house-&amp;gt;setKitchen(&quot;Modular Kitchen&quot;);
 }

 void buildFloor()
 {
  house-&amp;gt;setFloor(&quot;Wooden Floor&quot;);
 }

 House* getHouse()
 {
  return this-&amp;gt;house;
 }
};

/* Another Concrete class for the builder interface */
class NormalHouse:public HouseBuilder{
private:
 House *house;
public:
 NormalHouse()
 {
  house = new House();
 }

 void buildWindow()
 {
  house-&amp;gt;setWindow(&quot;Normal Window&quot;);
 }

 void buildDoor()
 {
  house-&amp;gt;setDoor(&quot;Metal Door&quot;);
 }

 void buildBathroom()
 {
  house-&amp;gt;setBathroom(&quot;Regular Bathroom&quot;);
 }

 void buildKitchen()
 {
  house-&amp;gt;setKitchen(&quot;Regular Kitchen&quot;);
 }

 void buildFloor()
 {
  house-&amp;gt;setFloor(&quot;Mosaic Floor&quot;);
 }

 House* getHouse()
 {
  return this-&amp;gt;house;
 }
};

/* The Director. Constructs the house */
class Contractor
{
private:
 HouseBuilder *houseBuilder;

public:
 Contractor(HouseBuilder *houseBuilder)
 {
  this-&amp;gt;houseBuilder = houseBuilder;
 }

 House *getHouse()
 {
  return houseBuilder-&amp;gt;getHouse();
 }

 void buildHouse()
 {
  houseBuilder-&amp;gt;buildWindow();
  houseBuilder-&amp;gt;buildDoor();
  houseBuilder-&amp;gt;buildBathroom();
  houseBuilder-&amp;gt;buildKitchen();
  houseBuilder-&amp;gt;buildFloor();
 }
};

/* Example on how to use the Builder design pattern */
int main()
{
 HouseBuilder *lavishHouseBldr = new LavishHouse();
 HouseBuilder *normalHouseBldr = new NormalHouse();

 Contractor *ctr1 = new Contractor(lavishHouseBldr);
 Contractor *ctr2 = new Contractor(normalHouseBldr);

 ctr1-&amp;gt;buildHouse();
 House *house1 = ctr1-&amp;gt;getHouse();
 cout&amp;lt;&amp;lt;&quot;Constructed: &quot;&amp;lt;&amp;lt;house1;

 ctr2-&amp;gt;buildHouse();
 House *house2 = ctr2-&amp;gt;getHouse();
 cout&amp;lt;&amp;lt;&quot;Constructed: &quot;&amp;lt;&amp;lt;house2;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;</description><link>http://simplestcodings.blogspot.com/2014/04/builder-design-pattern-implementation.html</link><author>noreply@blogger.com (Varun)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgPCuiSYtUz_LTTio4VHshLte_KO0DWfRso2jryCVDwLdee0Oh913-33V4M84BoMHb9twa8IV1WT005VGeNtCwYJRCwOTJBWkIqc33AoY0rlYmwgEVLZ771k4yhcKO55oXy6j6dPgBJBzI/s72-c/Builder.png" height="72" width="72"/><thr:total>7</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-3459284654925679524.post-3420951306635762427</guid><pubDate>Sun, 29 Dec 2013 14:46:00 +0000</pubDate><atom:updated>2023-12-21T00:04:21.166+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">Decorator Design Pattern</category><category domain="http://www.blogger.com/atom/ns#">Design Patterns</category><title>Decorator Design Pattern Implementation in C++</title><description>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
Do you need to extend the capabilities of your existing class instance at run-time? If the answer is yes then Decorator design pattern just provides the functionality you need.&lt;br /&gt;
&lt;br /&gt;
When we have to change the capabilities of only a particular instance and not all the instances which will get created for a particular class, we have to use decorator design pattern.&lt;br /&gt;
&lt;br /&gt;
This is achieved by creating a decorator class, which wraps the original class. The original class is sub-classed into two parts. One is the concrete class which is essentially the original class with only basic features. The other one is the Decorator base class. This decorator base class implements the same interface as the original class. In addition it wraps the original base class.&lt;br /&gt;
&lt;br /&gt;
We can extend this Decorator base class to create multiple concrete decorator classes. Each of these concrete decorator classes implement their own methods and will call the base class&#39;s instance&#39;s method.&lt;br /&gt;
&lt;br /&gt;
Now this looks complete babbling. Let&#39;s see what I mean actually.&lt;br /&gt;
&lt;br /&gt;
&lt;table align=&quot;center&quot; cellpadding=&quot;0&quot; cellspacing=&quot;0&quot; class=&quot;tr-caption-container&quot; style=&quot;margin-left: auto; margin-right: auto; text-align: center;&quot;&gt;&lt;tbody&gt;
&lt;tr&gt;&lt;td style=&quot;text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiXtn5jOf6MH7fEQ8P-Md9cLVNV6va5hgmZ4YdgVERv_t8zncKzaMCba0CJXZC07judkq33n3nYqI7oMhe8GHJqFDe5aG3xvWVu-uimFBQa7PvcrLyGe-Mw5bxyK1U8kKtYM272Vbaz1k8/s1600/dec_1.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: auto; margin-right: auto;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiXtn5jOf6MH7fEQ8P-Md9cLVNV6va5hgmZ4YdgVERv_t8zncKzaMCba0CJXZC07judkq33n3nYqI7oMhe8GHJqFDe5aG3xvWVu-uimFBQa7PvcrLyGe-Mw5bxyK1U8kKtYM272Vbaz1k8/s640/dec_1.png&quot; height=&quot;504&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td class=&quot;tr-caption&quot; style=&quot;text-align: center;&quot;&gt;Decorator Design Pattern&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;br /&gt;
I know the above diagram looks overwhelming. So let&#39;s explain it in more simple language with much simpler example.&lt;br /&gt;
&lt;br /&gt;
Lets prepare a subway burger. Shall we ;)&lt;br /&gt;
Now we all know that when we visit a Subway store, we have a variety of options to customize our Sub.&lt;br /&gt;
Assuming that we have chosen a foot-long already for the base bread, we start making our sandwich.&lt;br /&gt;
&lt;br /&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;We can add cheese to the sandwich.&lt;/li&gt;
&lt;li&gt;We can add vegetables to our Sub.&lt;/li&gt;
&lt;li&gt;We can add mayonnaise,mustard, sweet onion etc .&lt;/li&gt;
&lt;/ul&gt;
&lt;br /&gt;
Depending on our choices, the sandwich is prepared. And we are ready to eat it .. Aren&#39;t we :)&lt;br /&gt;
&lt;br /&gt;
Now consider the bread(foot-long) as the Base&amp;nbsp;Component&amp;nbsp;Class. Over this component, we can place a Decorator Base Class SubDecorator and now the Concrete Decorators can be derived from this class.&lt;br /&gt;
&lt;br /&gt;
CheeseDecorator, VegDecorator, SauceDecorator are concrete decorators which implement their own functions and have their own members in addition to the base class functions cost() and description().&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhbd1vZ3_Foqqkh3WErpSjOUbRS447SF8l3EM1AU_A4J6qyBARABImrYKdb2jHFV1Ug7hUlVKArgHN9GRwK5ORJKRHdWodTgZgJ0LG47c3cNSJNq4j91idzt1XygsK14KPkdFHBJjPbmNA/s1600/dec_2.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhbd1vZ3_Foqqkh3WErpSjOUbRS447SF8l3EM1AU_A4J6qyBARABImrYKdb2jHFV1Ug7hUlVKArgHN9GRwK5ORJKRHdWodTgZgJ0LG47c3cNSJNq4j91idzt1XygsK14KPkdFHBJjPbmNA/s640/dec_2.png&quot; height=&quot;419&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
And here comes the code:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;h1&gt;Decorator Design Pattern Implementation (C++)&lt;/h1&gt;
&lt;pre class=&quot;prettyprint&quot;&gt; &lt;code class=&quot;language-cpp&quot;&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;string&amp;gt;

//Uncomment the next line to enable debug logs
//#define DEBUG

std::string c(const std::string cls) {
    return &quot;\n&quot; + cls + &quot; Constructor&quot;;
}
std::string d(const std::string cls) {
    return &quot;\n&quot; +cls + &quot; Destructor&quot;;
}

/*Base component class*/
class Sandwich
{
public:
    virtual ~Sandwich() { }
    virtual double getCost()=0;
    virtual std::string getDesc()=0;
};

/*Concrete component class*/
class WheatBread:public Sandwich
{
public:
    WheatBread() {
#ifdef DEBUG
        std::cout&amp;lt;&amp;lt;c(&quot;WheatBread&quot;);
#endif
    }
    ~WheatBread() {
#ifdef DEBUG
        std::cout&amp;lt;&amp;lt;d(&quot;WheatBread&quot;);
#endif
    }
    std::string getDesc()
    {
        return &quot;Wheat Bread&quot;;
    }

    double getCost()
    {
        return 2.0;
    }
};

/*Concrete component class*/
class WholeGrainBread:public Sandwich
{
public:
    WholeGrainBread() {
#ifdef DEBUG
        std::cout&amp;lt;&amp;lt;c(&quot;WholeGrainBread&quot;);
#endif
    }
    ~WholeGrainBread() {
#ifdef DEBUG
        std::cout&amp;lt;&amp;lt;d(&quot;WholeGrainBread&quot;);
#endif
    }
    std::string getDesc()
    {
        return &quot;WholeGrain Bread&quot;;
    }

    double getCost()
    {
        return 3.0;
    }
};

/*Concrete component class*/
class ItalianBread:public Sandwich
{
public:
    ItalianBread() {
#ifdef DEBUG
        std::cout&amp;lt;&amp;lt;c(&quot;ItalianBread&quot;);
#endif
    }
    ~ItalianBread() {
#ifdef DEBUG
        std::cout&amp;lt;&amp;lt;d(&quot;ItalianBread&quot;);
#endif
    }
    std::string getDesc()
    {
        return &quot;Italian Bread&quot;;
    }

    double getCost()
    {
        return 2.5;
    }
};

/*Decorator Base class*/
class SubDecorator: public Sandwich
{
    Sandwich *sandwich;
public:
    SubDecorator(Sandwich *sandwichRef)
    {
#ifdef DEBUG
        std::cout&amp;lt;&amp;lt;c(&quot;SubDecorator&quot;);
#endif
        sandwich = sandwichRef;
    }

    ~SubDecorator() {
#ifdef DEBUG
        std::cout&amp;lt;&amp;lt;d(&quot;SubDecorator&quot;);
#endif
        delete sandwich;
    }
    double getCost()
    {
        return sandwich-&amp;gt;getCost();
    }
    std::string getDesc()
    {
        return sandwich-&amp;gt;getDesc();
    }
};

/*Decorator concrete class*/
class CheeseDecorator:public SubDecorator
{
private:
    std::string cheese_desc()
    {
        return &quot; + Cheese&quot;;
    }

    double cheese_cost;

public:
    CheeseDecorator(Sandwich *sandwich):SubDecorator(sandwich)
    {
#ifdef DEBUG
        std::cout&amp;lt;&amp;lt;c(&quot;CheeseDecorator&quot;);
#endif
        cheese_cost = 3.0;
    }

    ~CheeseDecorator() {
#ifdef DEBUG
        std::cout&amp;lt;&amp;lt;d(&quot;CheeseDecorator&quot;);
#endif
    }
    std::string getDesc()
    {
        return SubDecorator::getDesc().append(cheese_desc());
    }

    double getCost()
    {
        return SubDecorator::getCost() + cheese_cost;
    }
};

/*Decorator concrete class*/
class VegDecorator:public SubDecorator
{
private:
    std::string veg_desc()
    {
        return &quot; + Veg&quot;;
    }

    double veg_cost;

public:
    VegDecorator(Sandwich *sandwich):SubDecorator(sandwich)
    {
#ifdef DEBUG
        std::cout&amp;lt;&amp;lt;c(&quot;VegDecorator&quot;);
#endif
        veg_cost = 2.0;
    }

    ~VegDecorator() {
#ifdef DEBUG
        std::cout&amp;lt;&amp;lt;d(&quot;VegDecorator&quot;);
#endif
    }
    std::string getDesc()
    {
        return SubDecorator::getDesc().append(veg_desc());
    }

    double getCost()
    {
        return SubDecorator::getCost() + veg_cost;
    }
};

/*Decorator concrete class*/
class SauceDecorator:public SubDecorator
{
private:
    std::string sauce_desc()
    {
        return &quot; + Sauce&quot;;
    }

    double sauce_cost;

public:
    SauceDecorator(Sandwich *sandwich):SubDecorator(sandwich)
    {
#ifdef DEBUG
        std::cout&amp;lt;&amp;lt;c(&quot;SauceDecorator&quot;);
#endif
        sauce_cost = .5;
    }

    ~SauceDecorator() {
#ifdef DEBUG
        std::cout&amp;lt;&amp;lt;d(&quot;SauceDecorator&quot;);
#endif
    }
    std::string getDesc()
    {
        return SubDecorator::getDesc().append(sauce_desc());
    }

    double getCost()
    {
        return SubDecorator::getCost() + sauce_cost;
    }
};

int main()
{
    Sandwich *sandwich = new CheeseDecorator(new WheatBread());
    sandwich = new VegDecorator(sandwich);
    sandwich = new SauceDecorator(new SubDecorator(sandwich));
    std::cout&amp;lt;&amp;lt;&quot;\nYour sandwich is &quot;&amp;lt;&amp;lt;sandwich-&amp;gt;getDesc()&amp;lt;&amp;lt;&quot; and costs $&quot;&amp;lt;&amp;lt;sandwich-&amp;gt;getCost();
    delete sandwich;
}

&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;</description><link>http://simplestcodings.blogspot.com/2013/12/decorator-design-pattern-implementation-in-cplusplus.html</link><author>noreply@blogger.com (Varun)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiXtn5jOf6MH7fEQ8P-Md9cLVNV6va5hgmZ4YdgVERv_t8zncKzaMCba0CJXZC07judkq33n3nYqI7oMhe8GHJqFDe5aG3xvWVu-uimFBQa7PvcrLyGe-Mw5bxyK1U8kKtYM272Vbaz1k8/s72-c/dec_1.png" height="72" width="72"/><thr:total>14</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-3459284654925679524.post-5727076864756599282</guid><pubDate>Sun, 29 Dec 2013 11:08:00 +0000</pubDate><atom:updated>2023-12-21T00:23:22.969+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">Design Patterns</category><category domain="http://www.blogger.com/atom/ns#">Factory Method Design Pattern</category><title>Factory Method Design Pattern implementation in C++</title><description>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
What does a factory mean ? It is something which creates/manufactures some products.&lt;br /&gt;&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgyw9di-SpP3jdr-P5iDprZQ94T84yX_1H2N26wLefq5_eNcvuSme1l3c8qKHFUJ7E8I6olGt1-wbSnvDJNC412mGJrY3bqEqURLpGzm0YpA622wBXTIk0fxedrgk13_4g1SlER_LvypSJ6hiSSoqUcQ40ShMH_iU0CB2eTns2GYV3OYLRtglBtgxIZ0HI/s1024/factory.jpeg&quot; style=&quot;display: block; padding: 1em 0px; text-align: center;&quot;&gt;&lt;img alt=&quot;&quot; border=&quot;0&quot; data-original-height=&quot;1024&quot; data-original-width=&quot;1024&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgyw9di-SpP3jdr-P5iDprZQ94T84yX_1H2N26wLefq5_eNcvuSme1l3c8qKHFUJ7E8I6olGt1-wbSnvDJNC412mGJrY3bqEqURLpGzm0YpA622wBXTIk0fxedrgk13_4g1SlER_LvypSJ6hiSSoqUcQ40ShMH_iU0CB2eTns2GYV3OYLRtglBtgxIZ0HI/s400/factory.jpeg&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;  
&lt;div&gt;
Same is the job of factory design pattern. It is responsible for instantiation/creation of objects. But wait, isn&#39;t that something what constructors do ? Yes call to constructor indeed creates the object and that&#39;s exactly what a factory method does but with an additional feature of option of choosing between different constructors based on some logic.&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
Factory methods decide logically what constructor to call. So, instead of directly calling the constructor for a class, we call a factory method to get the object. There can be multiple derived classes from a base class. The factory method instantiates the appropriate sub-class based on the arguments passed to it and returns the base class type. This base class object can be used to access the derived class members/methods.&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
Blah, blah, blah... Let&#39;s get down to business and understand what it actually is and what it does.&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
A basic structure:&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;table align=&quot;center&quot; cellpadding=&quot;0&quot; cellspacing=&quot;0&quot; class=&quot;tr-caption-container&quot; style=&quot;margin-left: auto; margin-right: auto; text-align: center;&quot;&gt;&lt;tbody&gt;
&lt;tr&gt;&lt;td style=&quot;text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiCo7Hv7tdFun2M4ZrQbM06J3mQMAGCJgsFuntmZFRkepil8JGQnEpexkCHEcTVPkshq-tuARyZWZoRQ6KtuHPYTAENp0fqxgtupMMF1Un7xl0Lhb4U1sHIbSnYL5mRjJsTKdDnymZrFnY/s1600/factory_1.png&quot; style=&quot;margin-left: auto; margin-right: auto;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;384&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiCo7Hv7tdFun2M4ZrQbM06J3mQMAGCJgsFuntmZFRkepil8JGQnEpexkCHEcTVPkshq-tuARyZWZoRQ6KtuHPYTAENp0fqxgtupMMF1Un7xl0Lhb4U1sHIbSnYL5mRjJsTKdDnymZrFnY/s640/factory_1.png&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td class=&quot;tr-caption&quot; style=&quot;text-align: center;&quot;&gt;Basic structure of factory design pattern&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
Now let&#39;s explain it with a simple example:&lt;/div&gt;
&lt;div&gt;
Assume that we are an online Music Store . We every kind of music be it Rock, Classical, Jazz, Reggae, Techno and what not. Of course, to organize these we need categories based on different genres. Lets design this model using factory design pattern. Our base class is what we do. We provide music, so say &quot;Music&quot; is our base class.&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
Now Music can be classified into multiple categories . We for the time being assume only three.&lt;/div&gt;
&lt;div&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;Rock&lt;/li&gt;
&lt;li&gt;Pop&lt;/li&gt;
&lt;li&gt;Reggae&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div&gt;
The class structure would be something like this:&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;table align=&quot;center&quot; cellpadding=&quot;0&quot; cellspacing=&quot;0&quot; class=&quot;tr-caption-container&quot; style=&quot;margin-left: auto; margin-right: auto; text-align: center;&quot;&gt;&lt;tbody&gt;
&lt;tr&gt;&lt;td style=&quot;text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhJTP15JUjlBQukhAlP3slfHwYjy4AltdGHjx8i63zSwyWTd27zOul70v3ARg4W-TQj0wR8QjiFxy7CEHZUx7PtMajfTHThXEJ0wm2o-J6rWTo4EBzarRqyXt03XrUednda4T3AMJK2q-U/s1600/factory_2.png&quot; style=&quot;margin-left: auto; margin-right: auto;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;265&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhJTP15JUjlBQukhAlP3slfHwYjy4AltdGHjx8i63zSwyWTd27zOul70v3ARg4W-TQj0wR8QjiFxy7CEHZUx7PtMajfTHThXEJ0wm2o-J6rWTo4EBzarRqyXt03XrUednda4T3AMJK2q-U/s640/factory_2.png&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td class=&quot;tr-caption&quot; style=&quot;text-align: center;&quot;&gt;Class Structure&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;/div&gt;
Here &lt;i&gt;Rock&lt;/i&gt;, &lt;i&gt;Pop &lt;/i&gt;and &lt;i&gt;Reggae &lt;/i&gt;are the derived classes from base class &lt;b&gt;Music&lt;/b&gt;.&lt;br /&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
We create a factory pattern for this class structure in which we provide a factory method getMusic(genre_e genre) to the user. Using this method, one can instantiate the object of any subclass by choosing the genre.&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
Here genre is the logic based on which any particular subclass is instantiated. Advantage of this pattern is that outer world need not instantiate specific objects using the different sub-class constructors. It is being masked in the implementation of factory method.&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;table align=&quot;center&quot; cellpadding=&quot;0&quot; cellspacing=&quot;0&quot; class=&quot;tr-caption-container&quot; style=&quot;margin-left: auto; margin-right: auto; text-align: center;&quot;&gt;&lt;tbody&gt;
&lt;tr&gt;&lt;td style=&quot;text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiMLDskN4O7Zu8YWew4fcu_nxnMjl6wdifMo2bHToDY48HTbY7SaeA8g-ESUnESG50pzfu-NRl4GupCAn11pMFGh1Ye0_0a5Nvc3oWjZBdAlTsEVGA3hPsXAy7dvUyJQkr95s3GyCaxqn8/s1600/factory_3.png&quot; style=&quot;margin-left: auto; margin-right: auto;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;435&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiMLDskN4O7Zu8YWew4fcu_nxnMjl6wdifMo2bHToDY48HTbY7SaeA8g-ESUnESG50pzfu-NRl4GupCAn11pMFGh1Ye0_0a5Nvc3oWjZBdAlTsEVGA3hPsXAy7dvUyJQkr95s3GyCaxqn8/s640/factory_3.png&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td class=&quot;tr-caption&quot; style=&quot;text-align: center;&quot;&gt;Factory pattern for the class Music&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;div&gt;
Moreover if any new genre needs to be added, that can be done easily just by adding a new case in Factory method.&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
And now the code :&lt;/div&gt;
&lt;h1&gt;Factory Method Design Pattern implementation (C++)&lt;/h1&gt;
&lt;pre class=&quot;prettyprint&quot;&gt; &lt;code class=&quot;language-cpp&quot;&gt;#include &amp;lt;iostream&amp;gt;
using namespace std;

enum genre_e{ROCK,POP, REGGAE, INVALID};

/*Base Class*/
class Music {
public:
 virtual void song() = 0;
};

/*Derived class Rock from Music*/
class Rock: public Music
{
public:
 void song()
 {
  cout&amp;lt;&amp;lt;&quot;Nirvana: Smells like a teen spirit\n&quot;;
 }
};

/*Derived class Pop from Music*/
class Pop: public Music
{
public:
 void song()
 {
  cout&amp;lt;&amp;lt;&quot;Michael Jackson: Billie Jean\n&quot;;
 }
};

/*Derived class Reggae from Music*/
class Reggae: public Music
{
public:
 void song()
 {
  cout&amp;lt;&amp;lt;&quot;Bob Marley: No woman, No cry\n&quot;;
 }
};

/*Factory Class*/
class MusicFactory
{
public:
 /*Factory Method*/
 Music *getMusic(genre_e genre)
 {
  Music *music = NULL;

  /*Logic based on Genre*/
  switch(genre)
  {
  case ROCK:
   music = new Rock();
   break;
  case POP:
   music = new Pop();
   break;
  case REGGAE:
   music = new Reggae();
   break;
  default:
   music = NULL;
   break;
  }
  return music;
 }
};

int main()
{
 /*Create factory*/
 MusicFactory *musicFactory = new MusicFactory();

 /*Factory instantiating an object of type ROCK*/
 Music *music = musicFactory-&amp;gt;getMusic(ROCK);

 cout&amp;lt;&amp;lt;&quot;Song: &quot;;
 if(music)
  music-&amp;gt;song();
 else
  cout&amp;lt;&amp;lt;&quot;Wrong selection dude/dudette !!&quot;;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;</description><link>http://simplestcodings.blogspot.com/2013/12/factory-method-design-pattern-in-cplusplus.html</link><author>noreply@blogger.com (Varun)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgyw9di-SpP3jdr-P5iDprZQ94T84yX_1H2N26wLefq5_eNcvuSme1l3c8qKHFUJ7E8I6olGt1-wbSnvDJNC412mGJrY3bqEqURLpGzm0YpA622wBXTIk0fxedrgk13_4g1SlER_LvypSJ6hiSSoqUcQ40ShMH_iU0CB2eTns2GYV3OYLRtglBtgxIZ0HI/s72-c/factory.jpeg" height="72" width="72"/><thr:total>6</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-3459284654925679524.post-2038718705840192646</guid><pubDate>Sun, 29 Sep 2013 12:01:00 +0000</pubDate><atom:updated>2023-12-21T00:09:42.295+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">BFS</category><category domain="http://www.blogger.com/atom/ns#">DAG</category><category domain="http://www.blogger.com/atom/ns#">DFS</category><category domain="http://www.blogger.com/atom/ns#">Graphs</category><category domain="http://www.blogger.com/atom/ns#">Quiver</category><title>Graph Implementation in C</title><description>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
A graph is a collection of nodes and edges. These nodes are connected by links(edges).&lt;br /&gt;
These edges may be directed or undirected. Moreover these edges can have weights associated with them&lt;br /&gt;
&lt;br /&gt;
So edges can be categorized as :&lt;br /&gt;
&lt;ol style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;Directed, weighted edges&lt;/li&gt;
&lt;li&gt;Directed, unweighted edges&lt;/li&gt;
&lt;li&gt;Undirected, weighted edges&lt;/li&gt;
&lt;li&gt;Undirected, unweighted edges&lt;/li&gt;
&lt;/ol&gt;
&lt;div&gt;
&lt;b&gt;&lt;br /&gt;&lt;/b&gt;
&lt;br /&gt;
&lt;h2&gt;
&lt;span style=&quot;font-size: large;&quot;&gt;Uses of graphs&lt;/span&gt;&lt;/h2&gt;
Graphs are extremely useful. Look everywhere and one can easily find use of graphs. Listed below are a few of the vast set of practical uses of graphs.&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;table align=&quot;center&quot; cellpadding=&quot;0&quot; cellspacing=&quot;0&quot; class=&quot;tr-caption-container&quot; style=&quot;margin-left: auto; margin-right: auto; text-align: center;&quot;&gt;&lt;tbody&gt;
&lt;tr&gt;&lt;td style=&quot;text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgXSqdZdeGbFjp3Cpwdr9KeyhszF_rwBfqxmYcGdgYF8OlkWo2Pni8kwmNu8uW4g5m9QVYjVm4pBNhl3mRU23nKsMmakozNmJ80GmL7Cy-zVAx0sopUOg35zuMEURm4A67Sd_28EnDT1wU/s1600/dmrc.jpg&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: auto; margin-right: auto;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgXSqdZdeGbFjp3Cpwdr9KeyhszF_rwBfqxmYcGdgYF8OlkWo2Pni8kwmNu8uW4g5m9QVYjVm4pBNhl3mRU23nKsMmakozNmJ80GmL7Cy-zVAx0sopUOg35zuMEURm4A67Sd_28EnDT1wU/s640/dmrc.jpg&quot; height=&quot;524&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td class=&quot;tr-caption&quot; style=&quot;text-align: center;&quot;&gt;Delhi Metro Rail Map&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&amp;nbsp;Each station is a vertex, the distance in between is a weighted edge.&lt;br /&gt;
&lt;br /&gt;
&lt;table align=&quot;center&quot; cellpadding=&quot;0&quot; cellspacing=&quot;0&quot; class=&quot;tr-caption-container&quot; style=&quot;margin-left: auto; margin-right: auto; text-align: center;&quot;&gt;&lt;tbody&gt;
&lt;tr&gt;&lt;td style=&quot;text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhpY-LKsV1OQS4CLcoKVuFNrPnzGKplXd0MC9w8WLQfP855PhGm6nuxPxf7Rf3Ku8QqtjplRBihknpaIvV3z6izGQVkudO1wQxUbpei_QzKTolE0re1hMBXq8_WcVzwQVKYuzyYOEL9jA0/s1600/maze.gif&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: auto; margin-right: auto;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhpY-LKsV1OQS4CLcoKVuFNrPnzGKplXd0MC9w8WLQfP855PhGm6nuxPxf7Rf3Ku8QqtjplRBihknpaIvV3z6izGQVkudO1wQxUbpei_QzKTolE0re1hMBXq8_WcVzwQVKYuzyYOEL9jA0/s320/maze.gif&quot; height=&quot;320&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td class=&quot;tr-caption&quot; style=&quot;text-align: center;&quot;&gt;A Maze&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&amp;nbsp;Each corner is a vertex, Line between two corners is and edge.&lt;br /&gt;
&lt;br /&gt;
&lt;table align=&quot;center&quot; cellpadding=&quot;0&quot; cellspacing=&quot;0&quot; class=&quot;tr-caption-container&quot; style=&quot;margin-left: auto; margin-right: auto; text-align: center;&quot;&gt;&lt;tbody&gt;
&lt;tr&gt;&lt;td style=&quot;text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEicYvAmE16kInTqNgfO5YXaoyBrcDNDz5KgGPOGfvRgSdkk61mLtJVk2i34kV9wpfDlFMCghOMC23CRcgDYgoZeNPIHFm8gj1rlh_B9gOLK7kGh2Jx0g73TK7etO6N4eK5Rw-V-jcEGuD8/s1600/Tournament.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: auto; margin-right: auto;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEicYvAmE16kInTqNgfO5YXaoyBrcDNDz5KgGPOGfvRgSdkk61mLtJVk2i34kV9wpfDlFMCghOMC23CRcgDYgoZeNPIHFm8gj1rlh_B9gOLK7kGh2Jx0g73TK7etO6N4eK5Rw-V-jcEGuD8/s640/Tournament.png&quot; height=&quot;494&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td class=&quot;tr-caption&quot; style=&quot;text-align: center;&quot;&gt;A tournament fixture&lt;br /&gt;
Courtesy:&amp;nbsp;&lt;a href=&quot;http://www.squadtd.com/&quot;&gt;http://www.squadtd.com/&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;div&gt;
Each team is a vertex, match between the teams is an edge.&lt;/div&gt;
&lt;div&gt;
&lt;b&gt;&lt;br /&gt;&lt;/b&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;div&gt;
&lt;h2&gt;
&lt;b&gt;&lt;span style=&quot;font-size: large;&quot;&gt;Kind of graphs&lt;/span&gt;&lt;/b&gt;&lt;/h2&gt;
&lt;/div&gt;
&lt;div&gt;
There are numerous classifications and types of graphs available. I have collected a few of those types from various sources and organized a list of types of graphs:&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div style=&quot;text-align: left;&quot;&gt;
&lt;h3&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;&lt;b&gt;Undirected Graphs&lt;/b&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/h3&gt;
&lt;table align=&quot;center&quot; cellpadding=&quot;0&quot; cellspacing=&quot;0&quot; class=&quot;tr-caption-container&quot; style=&quot;margin-left: auto; margin-right: auto; text-align: center;&quot;&gt;&lt;tbody&gt;
&lt;tr&gt;&lt;td style=&quot;text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgmycfsD2KT69xNdFgNWSGfdmY8dh7Zu3pVhlJh461WtD6ZNq2FY9UUVwfeRUUG7I_1itjxTI_iTomDtQul3JvrHKnWOZPXsYtBHMH9ICm0Gm69dN9ycfJYLObjHvvWfFusqZdoXnPVNOI/s1600/undirected.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: auto; margin-right: auto;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgmycfsD2KT69xNdFgNWSGfdmY8dh7Zu3pVhlJh461WtD6ZNq2FY9UUVwfeRUUG7I_1itjxTI_iTomDtQul3JvrHKnWOZPXsYtBHMH9ICm0Gm69dN9ycfJYLObjHvvWfFusqZdoXnPVNOI/s1600/undirected.png&quot; /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td class=&quot;tr-caption&quot; style=&quot;text-align: center;&quot;&gt;Undirected Graph&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;div&gt;
&lt;b&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp;Characteristics:&lt;/b&gt;&lt;/div&gt;
&lt;ol style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;Order of vertices doesn&#39;t matter&lt;/li&gt;
&lt;li&gt;1-2 is same as 2-1&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;&lt;b&gt;Directed Graphs&lt;/b&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/h3&gt;
&lt;table align=&quot;center&quot; cellpadding=&quot;0&quot; cellspacing=&quot;0&quot; class=&quot;tr-caption-container&quot; style=&quot;margin-left: auto; margin-right: auto; text-align: center;&quot;&gt;&lt;tbody&gt;
&lt;tr&gt;&lt;td style=&quot;text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi1H8c9v3Qw9C_xULK28PEMd0XdyfgcSWYECEo1GAZWmvkF0VdI9bAoIYOIq_uVv6_xPfFkiOGThvGv8v7jIp4PsoT2hJpi6a2PmM4AS24EFZ4ZeBGdisQkQ1Iveb120twMv6RYbyx9TUs/s1600/directed.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: auto; margin-right: auto;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi1H8c9v3Qw9C_xULK28PEMd0XdyfgcSWYECEo1GAZWmvkF0VdI9bAoIYOIq_uVv6_xPfFkiOGThvGv8v7jIp4PsoT2hJpi6a2PmM4AS24EFZ4ZeBGdisQkQ1Iveb120twMv6RYbyx9TUs/s1600/directed.png&quot; /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td class=&quot;tr-caption&quot; style=&quot;text-align: center;&quot;&gt;Directed Graph&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;div&gt;
&lt;div&gt;
&lt;b&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp;Characteristics:&lt;/b&gt;&lt;/div&gt;
&lt;ol&gt;
&lt;li&gt;Order of vertices does matter&lt;/li&gt;
&lt;li&gt;1-2 is not same as 2-1&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;h3&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;&lt;b&gt;Vertex labeled Graphs.&lt;/b&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/h3&gt;
&lt;table align=&quot;center&quot; cellpadding=&quot;0&quot; cellspacing=&quot;0&quot; class=&quot;tr-caption-container&quot; style=&quot;margin-left: auto; margin-right: auto; text-align: center;&quot;&gt;&lt;tbody&gt;
&lt;tr&gt;&lt;td style=&quot;text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhLEry05wAP8m9al42Oap0FOeodGWTM5JTZeK98BZ2sQBKpIGu20PtAkaQ1_CFgEpN0xmzvZXKXc3MbD0X0-907Ah6DbQ7zjaK3Q-qLhHX0pE981TLny1mJbHVXh2gzUqrV-T5FelFvqQM/s1600/vertexlabeled.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: auto; margin-right: auto;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhLEry05wAP8m9al42Oap0FOeodGWTM5JTZeK98BZ2sQBKpIGu20PtAkaQ1_CFgEpN0xmzvZXKXc3MbD0X0-907Ah6DbQ7zjaK3Q-qLhHX0pE981TLny1mJbHVXh2gzUqrV-T5FelFvqQM/s1600/vertexlabeled.png&quot; /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td class=&quot;tr-caption&quot; style=&quot;text-align: center;&quot;&gt;Vertex Labeled Graph&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;div&gt;
&lt;div&gt;
&lt;b&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp;Characteristics:&lt;/b&gt;&lt;/div&gt;
&lt;ol&gt;
&lt;li&gt;Each vertex contains additional information. e.g {2,orange}, {4,green}&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;h3&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;&lt;b&gt;Cyclic Graphs.&lt;/b&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/h3&gt;
&lt;table align=&quot;center&quot; cellpadding=&quot;0&quot; cellspacing=&quot;0&quot; class=&quot;tr-caption-container&quot; style=&quot;margin-left: auto; margin-right: auto; text-align: center;&quot;&gt;&lt;tbody&gt;
&lt;tr&gt;&lt;td style=&quot;text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiw7bTnZILcmOOUjHdJXm1yMYTChBWdPimgd_VRAQ23si_pQP8wi7SqrANLdNXYMk_RbVYsTGXDF9CND3Xm0M3v-fmjDbbUIEdYStrB7nmVpnzOCtgQ5wi1K8X1bsUO0ygtic1aud5mP40/s1600/cyclic.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: auto; margin-right: auto;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiw7bTnZILcmOOUjHdJXm1yMYTChBWdPimgd_VRAQ23si_pQP8wi7SqrANLdNXYMk_RbVYsTGXDF9CND3Xm0M3v-fmjDbbUIEdYStrB7nmVpnzOCtgQ5wi1K8X1bsUO0ygtic1aud5mP40/s400/cyclic.png&quot; height=&quot;257&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td class=&quot;tr-caption&quot; style=&quot;text-align: center;&quot;&gt;Cyclic Graph&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;div&gt;
&lt;div&gt;
&lt;b&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp;Characteristics:&lt;/b&gt;&lt;/div&gt;
&lt;ol&gt;
&lt;li&gt;Graph contains at least one cycle.&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;h3&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;&lt;b&gt;Edge labeled Graphs.&lt;/b&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/h3&gt;
&lt;table align=&quot;center&quot; cellpadding=&quot;0&quot; cellspacing=&quot;0&quot; class=&quot;tr-caption-container&quot; style=&quot;margin-left: auto; margin-right: auto; text-align: center;&quot;&gt;&lt;tbody&gt;
&lt;tr&gt;&lt;td style=&quot;text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjH7QTRO61P1G_RFZmZja8ve468haA9IqoKvwL4mJSdiXEE23f8h4KpxlZ-lCLgfXG6zpOep9WncggOg2cOH-autHf9qvjuMrftxtgtAA0kvYDc61LFUr8vrXuwQl3b3-fBJpB4b6UzHME/s1600/edgelabeled.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: auto; margin-right: auto;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjH7QTRO61P1G_RFZmZja8ve468haA9IqoKvwL4mJSdiXEE23f8h4KpxlZ-lCLgfXG6zpOep9WncggOg2cOH-autHf9qvjuMrftxtgtAA0kvYDc61LFUr8vrXuwQl3b3-fBJpB4b6UzHME/s400/edgelabeled.png&quot; height=&quot;281&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td class=&quot;tr-caption&quot; style=&quot;text-align: center;&quot;&gt;Edge Labeled Graph&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;div&gt;
&lt;div&gt;
&lt;b&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp;Characteristics:&lt;/b&gt;&lt;/div&gt;
&lt;ol&gt;
&lt;li&gt;Edge has labels e.g an edge in the above graph will be represented as {orange,green,{blue,cyan}}&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;h3&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;&lt;b&gt;Weighted Graphs.&lt;/b&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/h3&gt;
&lt;table align=&quot;center&quot; cellpadding=&quot;0&quot; cellspacing=&quot;0&quot; class=&quot;tr-caption-container&quot; style=&quot;margin-left: auto; margin-right: auto; text-align: center;&quot;&gt;&lt;tbody&gt;
&lt;tr&gt;&lt;td style=&quot;text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj6yHKQ1pBizTvlbqZT5ZnN_GWBjXz5OYjYKaQVQUihLzP19bv601vhGKfAEtytDsFnju7UyGaADb7Bcg9Vg89WVbStBTht8FucPH1unT5D2WsobrTm0eA59P-C8sfp0Vai0kYleVueyd0/s1600/weighted.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: auto; margin-right: auto;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj6yHKQ1pBizTvlbqZT5ZnN_GWBjXz5OYjYKaQVQUihLzP19bv601vhGKfAEtytDsFnju7UyGaADb7Bcg9Vg89WVbStBTht8FucPH1unT5D2WsobrTm0eA59P-C8sfp0Vai0kYleVueyd0/s320/weighted.png&quot; height=&quot;315&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td class=&quot;tr-caption&quot; style=&quot;text-align: center;&quot;&gt;Weighted Graph&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;div&gt;
&lt;div&gt;
&lt;b&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp;Characteristics:&lt;/b&gt;&lt;/div&gt;
&lt;ol&gt;
&lt;li&gt;Each edge has some weight associated with it.&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;h3&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;&lt;b&gt;Directed Acyclic Graphs.&lt;/b&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/h3&gt;
&lt;table align=&quot;center&quot; cellpadding=&quot;0&quot; cellspacing=&quot;0&quot; class=&quot;tr-caption-container&quot; style=&quot;margin-left: auto; margin-right: auto; text-align: center;&quot;&gt;&lt;tbody&gt;
&lt;tr&gt;&lt;td style=&quot;text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjY8g67bcsep5ogzT8dtXN7i8dl7b1NQFCVo8k4S8NaUlI0ql3s2QQctkRQ4X6cARWPSqv1fOnquCRa0jZjjedBjcKNaOqaQeOcGk0h4vGJ1VzXxfBd9GDNNLALExvbHAmV_IB_RnhKvYI/s1600/dag.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: auto; margin-right: auto;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjY8g67bcsep5ogzT8dtXN7i8dl7b1NQFCVo8k4S8NaUlI0ql3s2QQctkRQ4X6cARWPSqv1fOnquCRa0jZjjedBjcKNaOqaQeOcGk0h4vGJ1VzXxfBd9GDNNLALExvbHAmV_IB_RnhKvYI/s400/dag.png&quot; height=&quot;257&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td class=&quot;tr-caption&quot; style=&quot;text-align: center;&quot;&gt;Direct Acyclic Graph(DAG)&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;div&gt;
&lt;div&gt;
&lt;b&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp;Characteristics:&lt;/b&gt;&lt;/div&gt;
&lt;ol&gt;
&lt;li&gt;Graph has no cycles.&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;h3&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;&lt;b&gt;Disconnected Graphs&lt;/b&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/h3&gt;
&lt;table align=&quot;center&quot; cellpadding=&quot;0&quot; cellspacing=&quot;0&quot; class=&quot;tr-caption-container&quot; style=&quot;margin-left: auto; margin-right: auto; text-align: center;&quot;&gt;&lt;tbody&gt;
&lt;tr&gt;&lt;td style=&quot;text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjG_RHRGT2ZteQsb_iX_1McURdDtSFByMysaRoRRjngmylmbpP2-XQWWVr2ik01DGrtqX7u8q8E_cfGFyKTCbinlVEMiAJkQ7p_qNycMC-5ARevZ9GeRhqNvYTHHOl2Y7IIUC0NppNy99s/s1600/disconnected.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: auto; margin-right: auto;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjG_RHRGT2ZteQsb_iX_1McURdDtSFByMysaRoRRjngmylmbpP2-XQWWVr2ik01DGrtqX7u8q8E_cfGFyKTCbinlVEMiAJkQ7p_qNycMC-5ARevZ9GeRhqNvYTHHOl2Y7IIUC0NppNy99s/s320/disconnected.png&quot; height=&quot;257&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td class=&quot;tr-caption&quot; style=&quot;text-align: center;&quot;&gt;Disconnected Graph&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;div&gt;
&lt;div&gt;
&lt;b&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp;Characteristics:&lt;/b&gt;&lt;/div&gt;
&lt;ol&gt;
&lt;li&gt;&lt;span style=&quot;font-family: inherit;&quot;&gt;Vertices are disconnected&amp;nbsp;&lt;/span&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;h3&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;&lt;b&gt;Mixed graph&lt;/b&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/h3&gt;
&lt;table align=&quot;center&quot; cellpadding=&quot;0&quot; cellspacing=&quot;0&quot; class=&quot;tr-caption-container&quot; style=&quot;margin-left: auto; margin-right: auto; text-align: center;&quot;&gt;&lt;tbody&gt;
&lt;tr&gt;&lt;td style=&quot;text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjWi6HcqeaQ_VHP15K9vvle5JrKjQoIjdk0il0ETBPofnFi0HUuxnYKj8sr9ehRDv7rgGUAu8l1i1KOJMvoh1lGphpRqBL3yeueL-daP5InglytK6vRh3LKK-jPMCMLxziYNApNM3LNvYs/s1600/mixed.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: auto; margin-right: auto;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjWi6HcqeaQ_VHP15K9vvle5JrKjQoIjdk0il0ETBPofnFi0HUuxnYKj8sr9ehRDv7rgGUAu8l1i1KOJMvoh1lGphpRqBL3yeueL-daP5InglytK6vRh3LKK-jPMCMLxziYNApNM3LNvYs/s320/mixed.png&quot; height=&quot;316&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td class=&quot;tr-caption&quot; style=&quot;text-align: center;&quot;&gt;Mixed Graph&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;div&gt;
&lt;div&gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp;&lt;b&gt;Characteristics:&lt;/b&gt;&lt;/div&gt;
&lt;ol&gt;
&lt;li&gt;&lt;span style=&quot;font-family: inherit;&quot;&gt;&lt;span style=&quot;background-color: white; line-height: 19.1875px;&quot;&gt;Some edges may be directed and some may be undirected&lt;/span&gt;&amp;nbsp;&lt;/span&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;h3&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;&lt;b&gt;Multigraph&lt;/b&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/h3&gt;
&lt;table align=&quot;center&quot; cellpadding=&quot;0&quot; cellspacing=&quot;0&quot; class=&quot;tr-caption-container&quot; style=&quot;margin-left: auto; margin-right: auto; text-align: center;&quot;&gt;&lt;tbody&gt;
&lt;tr&gt;&lt;td style=&quot;text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh0ZXOQJ7CwZMicZmn_5WZMqI96eljAfnSBijb-7E0HL5HBnJgByK-SykxkzzS-IwpBec9pE8N0-R0_rk4Le5J1_L3kRLZ-Ce8W1Y7P2GDiBG6tx4ZMJsvGC2u-Aq7enJmJZ3GBB79Sch0/s1600/multigraph.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: auto; margin-right: auto;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh0ZXOQJ7CwZMicZmn_5WZMqI96eljAfnSBijb-7E0HL5HBnJgByK-SykxkzzS-IwpBec9pE8N0-R0_rk4Le5J1_L3kRLZ-Ce8W1Y7P2GDiBG6tx4ZMJsvGC2u-Aq7enJmJZ3GBB79Sch0/s320/multigraph.png&quot; height=&quot;271&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td class=&quot;tr-caption&quot; style=&quot;text-align: center;&quot;&gt;Multigraph&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;div&gt;
&lt;div&gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp;&lt;b&gt;Characteristics:&lt;/b&gt;&lt;/div&gt;
&lt;ol&gt;
&lt;li&gt;&lt;span style=&quot;font-family: inherit;&quot;&gt;Multiple edges&lt;span style=&quot;background-color: white; line-height: 19.1875px;&quot;&gt;&amp;nbsp;(and sometimes loops) are allowed&lt;/span&gt;&lt;/span&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;b&gt;Quiver&lt;/b&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/h3&gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;&amp;nbsp;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiENvwF3WejqoX7JUFzYFBoYGlJ65WAXI-epNmQL43IDQyF26j2lBL7STUNeGGGv3e2AVyZpTY1tGEcw-KTdRo0DIxYVNeruqSn0cJmcQAuRu3bK9vpGRD9cNsoD9QPoH6SZt9ae49lOZbS/s1600/quiver.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em; text-align: center;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiENvwF3WejqoX7JUFzYFBoYGlJ65WAXI-epNmQL43IDQyF26j2lBL7STUNeGGGv3e2AVyZpTY1tGEcw-KTdRo0DIxYVNeruqSn0cJmcQAuRu3bK9vpGRD9cNsoD9QPoH6SZt9ae49lOZbS/s400/quiver.png&quot; height=&quot;356&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div style=&quot;text-align: left;&quot;&gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp;&lt;b&gt;Characteristics:&lt;/b&gt;&lt;br /&gt;
&lt;div&gt;
&lt;ol&gt;
&lt;li&gt;&lt;span style=&quot;background-color: white; line-height: 19.1875px;&quot;&gt;&lt;span style=&quot;font-family: inherit;&quot;&gt;Directed graph which may have more than one arrow from a given source to a given target. A quiver may also have directed loops in it.&lt;/span&gt;&lt;/span&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;
&lt;h2&gt;
&lt;b&gt;&lt;span style=&quot;font-size: large;&quot;&gt;Representation of graphs:&lt;/span&gt;&lt;/b&gt;&lt;/h2&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;
&lt;table align=&quot;center&quot; cellpadding=&quot;0&quot; cellspacing=&quot;0&quot; class=&quot;tr-caption-container&quot; style=&quot;margin-left: auto; margin-right: auto; text-align: center;&quot;&gt;&lt;tbody&gt;
&lt;tr&gt;&lt;td style=&quot;text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEirdUE_LP6I9-yyv7PSsl8Ml_jwE6sEvMjSuWCtHnlJoEvZi4OgcyQAle4qpn0_ED241uPNId62TmtANeE0W1lNIu6EwgEApAMeV_uj71vMfdZeTJVqFkZEeOsINYlv5cXtzhA-EDR58nI/s1600/adjacency.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: auto; margin-right: auto;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEirdUE_LP6I9-yyv7PSsl8Ml_jwE6sEvMjSuWCtHnlJoEvZi4OgcyQAle4qpn0_ED241uPNId62TmtANeE0W1lNIu6EwgEApAMeV_uj71vMfdZeTJVqFkZEeOsINYlv5cXtzhA-EDR58nI/s400/adjacency.png&quot; height=&quot;185&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td class=&quot;tr-caption&quot; style=&quot;text-align: center;&quot;&gt;Fig. 1: An undirected graph&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;table align=&quot;center&quot; cellpadding=&quot;0&quot; cellspacing=&quot;0&quot; class=&quot;tr-caption-container&quot; style=&quot;margin-left: auto; margin-right: auto; text-align: center;&quot;&gt;&lt;tbody&gt;
&lt;tr&gt;&lt;td style=&quot;text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgXRyck8oHv4oGKsSTV_04UlAZuxJ7zIh0srWepK_DE36bpdGQcK5yojW-j2sIVU6yuKsZf-YtsEXfXS6XmaIaXmEwnECQjcGBxiBXREZwapJ75sXy1nMgfJpECOYWSarvgLXfDau3jgN0/s1600/adjacency_dir.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: auto; margin-right: auto;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgXRyck8oHv4oGKsSTV_04UlAZuxJ7zIh0srWepK_DE36bpdGQcK5yojW-j2sIVU6yuKsZf-YtsEXfXS6XmaIaXmEwnECQjcGBxiBXREZwapJ75sXy1nMgfJpECOYWSarvgLXfDau3jgN0/s400/adjacency_dir.png&quot; height=&quot;185&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td class=&quot;tr-caption&quot; style=&quot;text-align: center;&quot;&gt;Fig 2: A directed graph&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
In order to use Graphs programatically , they need to be somehow represented in code. Following are the most widely used methods of representing a graph.&lt;br /&gt;
&lt;br /&gt;
&lt;h3&gt;
&lt;b&gt;&lt;u&gt;Adjacency Matrix :&lt;/u&gt;&amp;nbsp;&lt;/b&gt;&lt;/h3&gt;
&lt;/div&gt;
&lt;div&gt;
For N vertices an adjacency matrix is an NxN array A such that&lt;br /&gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;A[i][j] = 1 if there is an edge E(i,j)&lt;br /&gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; = 0 otherwise&lt;br /&gt;
&lt;br /&gt;
For an undirected graph, A[i][j] = A[j][i]&lt;br /&gt;
&lt;br /&gt;
For weighted graphs,&lt;br /&gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;A[i][j] = weight of the edge, if there is an edge E(i,j)&lt;br /&gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;= a constant representing no edge (e.g a very large or very small value)&lt;br /&gt;
&lt;br /&gt;
For Fig 1, the adjacency matrix would be&amp;nbsp;&lt;/div&gt;
&lt;table align=&quot;center&quot; cellpadding=&quot;0&quot; cellspacing=&quot;0&quot; class=&quot;tr-caption-container&quot; style=&quot;margin-left: auto; margin-right: auto; text-align: center;&quot;&gt;&lt;tbody&gt;
&lt;tr&gt;&lt;td style=&quot;text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjJhY9K-sebOVfJ6K0yQ7dhrYqttQiWyxYVT1H2KEgj1FuTxfHrIMKuRxHjzesl_8Ws4lDRu1vcEz3gILdDsHSXRyhMrR21sDRsG10lBODs-QPloYLjg78lL_qmTYbDVfSxSasvryuMadE/s1600/adjmatundirect.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: auto; margin-right: auto;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjJhY9K-sebOVfJ6K0yQ7dhrYqttQiWyxYVT1H2KEgj1FuTxfHrIMKuRxHjzesl_8Ws4lDRu1vcEz3gILdDsHSXRyhMrR21sDRsG10lBODs-QPloYLjg78lL_qmTYbDVfSxSasvryuMadE/s320/adjmatundirect.png&quot; height=&quot;273&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td class=&quot;tr-caption&quot; style=&quot;text-align: center;&quot;&gt;&lt;br /&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;div&gt;
The adjacency matrix for directed graph in Fig 2 would be:&lt;br /&gt;
&lt;div&gt;
&lt;br /&gt;
&lt;table align=&quot;center&quot; cellpadding=&quot;0&quot; cellspacing=&quot;0&quot; class=&quot;tr-caption-container&quot; style=&quot;margin-left: auto; margin-right: auto; text-align: center;&quot;&gt;&lt;tbody&gt;
&lt;tr&gt;&lt;td style=&quot;text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjIxaaVLVBlzGl144oc27WbjsoUM3xuw8gjcjCr36GuL2OXPrd8YeN84wp2ojRlyZMQ5HdbySScyYetKO3Ek5OBpsOzbrQR_AbwaSR7D02PoojWiXWzaiuaSZSSgRaQOTr2NyFq1uEUI_k/s1600/adjmatdirect.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: auto; margin-right: auto;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjIxaaVLVBlzGl144oc27WbjsoUM3xuw8gjcjCr36GuL2OXPrd8YeN84wp2ojRlyZMQ5HdbySScyYetKO3Ek5OBpsOzbrQR_AbwaSR7D02PoojWiXWzaiuaSZSSgRaQOTr2NyFq1uEUI_k/s320/adjmatdirect.png&quot; height=&quot;269&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td class=&quot;tr-caption&quot; style=&quot;text-align: center;&quot;&gt;&lt;br /&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;div style=&quot;text-align: left;&quot;&gt;
&lt;h3&gt;
&lt;b&gt;&lt;u&gt;Adjacency List :&lt;/u&gt;&amp;nbsp;&lt;/b&gt;&lt;/h3&gt;
&lt;/div&gt;
&lt;div style=&quot;text-align: left;&quot;&gt;
Adjacency matrix representation consume a lot of memory (O[N&lt;sup&gt;2&lt;/sup&gt;]). If the graph is complete or almost complete(i.e. contains most of the edges between the vertices), then this representation is good to use. But if there are very few edges as compared to number of vertices, it will unnecessarily consume extra space. Adjacency list can handle this situation very optimally.&lt;br /&gt;
&lt;br /&gt;
Every vertex has a linked list of the vertices it is connected with.&lt;/div&gt;
&lt;div style=&quot;text-align: left;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div style=&quot;text-align: left;&quot;&gt;
Adjacency list for Fig 1 would be:&lt;/div&gt;
&lt;div style=&quot;text-align: left;&quot;&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgzMZfq-dDnVjaTSx762Q4YZkvvGiirR7w60Fhb2wbg6wqZVnCzzaAiTXQSFXJkzo9VZ83FK4-Cy06izljG0ZAhMxPnKUfnHL1HkXj6Mdyp4pJh_QMAbUI_hAY025DNy5pmDLDYu50gj6c/s1600/adjlistundirect.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgzMZfq-dDnVjaTSx762Q4YZkvvGiirR7w60Fhb2wbg6wqZVnCzzaAiTXQSFXJkzo9VZ83FK4-Cy06izljG0ZAhMxPnKUfnHL1HkXj6Mdyp4pJh_QMAbUI_hAY025DNy5pmDLDYu50gj6c/s320/adjlistundirect.png&quot; height=&quot;265&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;/div&gt;
&lt;div style=&quot;text-align: left;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div style=&quot;text-align: left;&quot;&gt;
&lt;div&gt;
Adjacency list for Fig 2 would be:&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhzNE7YL4VEHRnMxWPOed4otFpevwkhmg7WSAIdLQajBPdhEvL-DOk9X1ePj3MFC52Nn5KJ_uLTQCHM51DPOe9OzUoEO7qn2iSwmu8RVKuBT7_bxlt-8cuAtFpO87UrPfptxVn4Rt0Y_6s/s1600/adjlistdirect.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhzNE7YL4VEHRnMxWPOed4otFpevwkhmg7WSAIdLQajBPdhEvL-DOk9X1ePj3MFC52Nn5KJ_uLTQCHM51DPOe9OzUoEO7qn2iSwmu8RVKuBT7_bxlt-8cuAtFpO87UrPfptxVn4Rt0Y_6s/s320/adjlistdirect.png&quot; height=&quot;265&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;
Following is code snippet to implement graphs in C using adjacency list.&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;&lt;code class=&quot;language-C&quot;&gt;/*graph.h*/
#ifndef _GRAPH_H_
#define _GRAPH_H_

typedef enum {UNDIRECTED=0,DIRECTED} graph_type_e;

/* Adjacency list node*/
typedef struct adjlist_node
{
    int vertex;                /*Index to adjacency list array*/
    struct adjlist_node *next; /*Pointer to the next node*/
}adjlist_node_t, *adjlist_node_p;

/* Adjacency list */
typedef struct adjlist
{
    int num_members;           /*number of members in the list (for future use)*/
    adjlist_node_t *head;      /*head of the adjacency linked list*/
}adjlist_t, *adjlist_p;

/* Graph structure. A graph is an array of adjacency lists.
   Size of array will be number of vertices in graph*/
typedef struct graph
{
    graph_type_e type;        /*Directed or undirected graph */
    int num_vertices;         /*Number of vertices*/
    adjlist_p adjListArr;     /*Adjacency lists&#39; array*/
}graph_t, *graph_p;

/* Exit function to handle fatal errors*/
__inline void err_exit(char* msg)
{
    printf(&quot;[Fatal Error]: %s \nExiting...\n&quot;, msg);
    exit(1);
}

#endif

&lt;/code&gt;&lt;/pre&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;&lt;code class=&quot;language-C&quot;&gt;/*graph.c*/
#include &amp;lt;stdio.h&amp;gt;
#include &amp;lt;stdlib.h&amp;gt;
#include &quot;graph.h&quot;

/* Function to create an adjacency list node*/
adjlist_node_p createNode(int v)
{
    adjlist_node_p newNode = (adjlist_node_p)malloc(sizeof(adjlist_node_t));
    if(!newNode)
        err_exit(&quot;Unable to allocate memory for new node&quot;);

    newNode-&amp;gt;vertex = v;
    newNode-&amp;gt;next = NULL;

    return newNode;
}

/* Function to create a graph with n vertices; Creates both directed and undirected graphs*/
graph_p createGraph(int n, graph_type_e type)
{
    int i;
    graph_p graph = (graph_p)malloc(sizeof(graph_t));
    if(!graph)
        err_exit(&quot;Unable to allocate memory for graph&quot;);
    graph-&amp;gt;num_vertices = n;
    graph-&amp;gt;type = type;

    /* Create an array of adjacency lists*/
    graph-&amp;gt;adjListArr = (adjlist_p)malloc(n * sizeof(adjlist_t));
    if(!graph-&amp;gt;adjListArr)
        err_exit(&quot;Unable to allocate memory for adjacency list array&quot;);

    for(i = 0; i &amp;lt; n; i++)
    {
        graph-&amp;gt;adjListArr[i].head = NULL;
        graph-&amp;gt;adjListArr[i].num_members = 0;
    }

    return graph;
}

/*Destroys the graph*/
void destroyGraph(graph_p graph)
{
    if(graph)
    {
        if(graph-&amp;gt;adjListArr)
        {
            int v;
            /*Free up the nodes*/
            for (v = 0; v &amp;lt; graph-&amp;gt;num_vertices; v++)
            {
                adjlist_node_p adjListPtr = graph-&amp;gt;adjListArr[v].head;
                while (adjListPtr)
                {
                    adjlist_node_p tmp = adjListPtr;
                    adjListPtr = adjListPtr-&amp;gt;next;
                    free(tmp);
                }
            }
            /*Free the adjacency list array*/
            free(graph-&amp;gt;adjListArr);
        }
        /*Free the graph*/
        free(graph);
    }
}

/* Adds an edge to a graph*/
void addEdge(graph_t *graph, int src, int dest)
{
    /* Add an edge from src to dst in the adjacency list*/
    adjlist_node_p newNode = createNode(dest);
    newNode-&amp;gt;next = graph-&amp;gt;adjListArr[src].head;
    graph-&amp;gt;adjListArr[src].head = newNode;
    graph-&amp;gt;adjListArr[src].num_members++;

    if(graph-&amp;gt;type == UNDIRECTED)
    {
        /* Add an edge from dest to src also*/
        newNode = createNode(src);
        newNode-&amp;gt;next = graph-&amp;gt;adjListArr[dest].head;
        graph-&amp;gt;adjListArr[dest].head = newNode;
        graph-&amp;gt;adjListArr[dest].num_members++;
    }
}

/* Function to print the adjacency list of graph*/
void displayGraph(graph_p graph)
{
    int i;
    for (i = 0; i &amp;lt; graph-&amp;gt;num_vertices; i++)
    {
        adjlist_node_p adjListPtr = graph-&amp;gt;adjListArr[i].head;
        printf(&quot;\n%d: &quot;, i);
        while (adjListPtr)
        {
            printf(&quot;%d-&amp;gt;&quot;, adjListPtr-&amp;gt;vertex);
            adjListPtr = adjListPtr-&amp;gt;next;
        }
        printf(&quot;NULL\n&quot;);
    }
}

int main()
{
    graph_p undir_graph = createGraph(5, UNDIRECTED);
    graph_p dir_graph = createGraph(5, DIRECTED);
    addEdge(undir_graph, 0, 1);
    addEdge(undir_graph, 0, 4);
    addEdge(undir_graph, 1, 2);
    addEdge(undir_graph, 1, 3);
    addEdge(undir_graph, 1, 4);
    addEdge(undir_graph, 2, 3);
    addEdge(undir_graph, 3, 4);

    addEdge(dir_graph, 0, 1);
    addEdge(dir_graph, 0, 4);
    addEdge(dir_graph, 1, 2);
    addEdge(dir_graph, 1, 3);
    addEdge(dir_graph, 1, 4);
    addEdge(dir_graph, 2, 3);
    addEdge(dir_graph, 3, 4);

    printf(&quot;\nUNDIRECTED GRAPH&quot;);
    displayGraph(undir_graph);
    destroyGraph(undir_graph);

    printf(&quot;\nDIRECTED GRAPH&quot;);
    displayGraph(dir_graph);
    destroyGraph(dir_graph);

    return 0;
}

&lt;/code&gt;&lt;/pre&gt;
&lt;br /&gt;
&lt;span style=&quot;font-size: x-small;&quot;&gt;Sources:&lt;/span&gt;&lt;br /&gt;
&lt;a href=&quot;http://en.wikipedia.org/wiki/Graph_(mathematics)&quot;&gt;&lt;span style=&quot;font-size: x-small;&quot;&gt;http://en.wikipedia.org/wiki/Graph_(mathematics)&lt;/span&gt;&lt;/a&gt;&lt;br /&gt;
&lt;a href=&quot;http://www.blogger.com/goog_1776275656&quot;&gt;&lt;span style=&quot;font-size: x-small;&quot;&gt;http://web.cecs.pdx.edu/~sheard/course/Cs163/Doc/Graphs.html&lt;/span&gt;&lt;/a&gt;&lt;br /&gt;
&lt;span style=&quot;font-size: x-small;&quot;&gt;&lt;a href=&quot;http://www.blogger.com/goog_1776275656&quot;&gt;http://msdn.microsoft.com/en-us/library/ms379574(v=vs.80).aspx&lt;/a&gt;&lt;/span&gt;&lt;br /&gt;
&lt;div class=&quot;fb-comments&quot; data-colorscheme=&quot;light&quot; data-href=&quot;http://simplestcodings.blogspot.in/2013/09/graphs.html&quot; data-numposts=&quot;5&quot; data-width=&quot;600&quot;&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
 SyntaxHighlighter.highlight();
&lt;/script&gt;&lt;/div&gt;
</description><link>http://simplestcodings.blogspot.com/2013/09/graphs.html</link><author>noreply@blogger.com (Varun)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgXSqdZdeGbFjp3Cpwdr9KeyhszF_rwBfqxmYcGdgYF8OlkWo2Pni8kwmNu8uW4g5m9QVYjVm4pBNhl3mRU23nKsMmakozNmJ80GmL7Cy-zVAx0sopUOg35zuMEURm4A67Sd_28EnDT1wU/s72-c/dmrc.jpg" height="72" width="72"/><thr:total>23</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-3459284654925679524.post-2390350933796851984</guid><pubDate>Thu, 08 Nov 2012 14:01:00 +0000</pubDate><atom:updated>2023-12-20T22:41:23.654+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">Trie</category><title>Trie implementation in C</title><description>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
To implement the kind of storage which stores strings as the search keys , there is a need to have special data structures which can store the strings efficiently and the searching of data based on the string keys is easier, efficient and faster. One such data structure is a tree based implementation called Trie.&lt;br /&gt;
&lt;br /&gt;
Trie is a data structure which can be used to implement a dictionary kind of application. It provides all the functionality to insert a string, search a string and delete a string from the dictionary. The insertion and deletion operation takes O(n) time where n is the length of the string to be deleted or inserted. &lt;br /&gt;
&lt;div&gt;
Some of the application of tries involve web based search engines, URL completion in autocomplete feature, Spell checker etc.&lt;/div&gt;
&lt;br /&gt;
&lt;h3&gt;
Structure of Trie(Specific to this implementation):&lt;/h3&gt;
The trie implemented here consists of nodes. Each node has these fields:&lt;br /&gt;
&lt;div&gt;
&lt;/div&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Key&lt;/strong&gt; - Part of the string to be serached,inserted or deleted.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Value&lt;/strong&gt; -&amp;nbsp; The value associated with a string (e.g In a dictionary it could be the meaning of the word which we are searching)&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Neighbour node address&lt;/strong&gt; - It consists of the address of the neighbouring node at the same level.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Previous neighbour address&lt;/strong&gt; - It consists of the address of the previous node at the same level.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Children node address&lt;/strong&gt; - It consists of the address of the child nodes of the current node.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Parent node address&lt;/strong&gt; - It consists of the address of the parent node of the current node.&lt;/li&gt;
&lt;/ol&gt;
The additional nodes like &lt;em&gt;Parent&lt;/em&gt; and &lt;em&gt;Previous&lt;/em&gt; nodes are added to this implementation for making the search, and deletions easier.&lt;br /&gt;
&lt;br /&gt;
Here is a diagrammatical view of a trie nodes I have used in this implementation. The field &lt;em&gt;key&lt;/em&gt; is not represented in the diagram due to symmetry purposes.&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgyyoXgdnY_8wmBey5E6MSZ_3CMr5F7AsPOVmIsyl4OMDfxSRNiF21clUJNgcJeFj_ES1lQdSxZjD_UlHPiOITmhZcrPOyTbzm7WgRaCaAxgbhFEho5p4gp1JqAS0-VM-ZxVepMBh18xxak/s1600/TrieNodes.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;512&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgyyoXgdnY_8wmBey5E6MSZ_3CMr5F7AsPOVmIsyl4OMDfxSRNiF21clUJNgcJeFj_ES1lQdSxZjD_UlHPiOITmhZcrPOyTbzm7WgRaCaAxgbhFEho5p4gp1JqAS0-VM-ZxVepMBh18xxak/s640/TrieNodes.png&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;div&gt;
&amp;nbsp;&amp;nbsp;&lt;/div&gt;
Let us consider an example to understand tries in detail.&lt;br /&gt;
&lt;br /&gt;
Suppose we have to implement a database for the HR department of an organisation in which we have to store an employee&#39;s name and their ages. There is an assumption for this example that there each employee&#39;s name is unique.So there is a strange policy in this organisation that any new employee which has a name that already exists in the organisation, it would not hire that new employee.&lt;br /&gt;
&lt;br /&gt;
Let&#39;s use this hypothetical example just to understand how tries work.&lt;br /&gt;
&lt;ul&gt;
&lt;li&gt;Consider we have a new employee named Andrew with age 36. Lets populate our trie for &quot;andrew&quot;.&lt;/li&gt;
&lt;/ul&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjRkQQIKdrMrc3lF7p0Ks5CsWafymMTIaAY2WNPvLcTufu8pNynGWQb51h9l3VfZsukSZAKquPKA39hXL_cMVVncgA2cFXtMNSOgrVqY4ZJbcWg8OJwCqfqovNm00KUmF2jnZKr85CIhlj9/s1600/Trie1.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;640&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjRkQQIKdrMrc3lF7p0Ks5CsWafymMTIaAY2WNPvLcTufu8pNynGWQb51h9l3VfZsukSZAKquPKA39hXL_cMVVncgA2cFXtMNSOgrVqY4ZJbcWg8OJwCqfqovNm00KUmF2jnZKr85CIhlj9/s640/Trie1.png&quot; width=&quot;88&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div align=&quot;center&quot;&gt;
﻿&lt;/div&gt;
&lt;br /&gt;
&lt;ul&gt;
&lt;li&gt;Now add &quot;tina&quot;.&lt;/li&gt;
&lt;/ul&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjQvqCBg3tOBaxGa0ZeDE1Q5I81zQOVMePIoxibP94UoUfK67hiac-e-MUA6jdx-Zm8OuWssUb6eeFccnSwB52uc-AuGCSl7Tk0r6eRxJROfRKjKHO8MTyNLhmsxxToUkjRcQVwbvZvwIKU/s1600/Trie2.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;640&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjQvqCBg3tOBaxGa0ZeDE1Q5I81zQOVMePIoxibP94UoUfK67hiac-e-MUA6jdx-Zm8OuWssUb6eeFccnSwB52uc-AuGCSl7Tk0r6eRxJROfRKjKHO8MTyNLhmsxxToUkjRcQVwbvZvwIKU/s640/Trie2.png&quot; width=&quot;144&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div align=&quot;center&quot;&gt;
&lt;/div&gt;
&lt;div align=&quot;center&quot;&gt;
&lt;/div&gt;
&lt;div align=&quot;center&quot;&gt;
﻿&lt;/div&gt;
&lt;ul&gt;
&lt;li&gt;Add &quot;argo&quot;.&lt;/li&gt;
&lt;/ul&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjPGQ1mmOXlDHfXXjpqM5sD8K1QG1V9XaZ4LIuuiFMFp1WINllNW8UcjdXtaWX10Vj80yqPB3fDmNDJYKa7J6dYIZ2jr7n47XY0h_Dbz0WAKBpUi5qeT6cyMeGIef_3n9yJinWmT8PuIgvQ/s1600/Trie3.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;640&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjPGQ1mmOXlDHfXXjpqM5sD8K1QG1V9XaZ4LIuuiFMFp1WINllNW8UcjdXtaWX10Vj80yqPB3fDmNDJYKa7J6dYIZ2jr7n47XY0h_Dbz0WAKBpUi5qeT6cyMeGIef_3n9yJinWmT8PuIgvQ/s640/Trie3.png&quot; width=&quot;218&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div align=&quot;center&quot;&gt;
﻿&lt;/div&gt;
&lt;ul&gt;
&lt;li&gt;Add &quot;tim&quot;.&lt;/li&gt;
&lt;/ul&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEikwMX3T3ux-bghDQEEgvFkxMf7zjG0lkcFH-EaAthCk7zJwrFAIyTEyBfym18ouiwj4I9u4_LliCGCGWxePJxKI-cn-x-TTnjEPH4GMz5dD1xDZsvafaPTigXXtr9p-SHTu5tuyVasmB0N/s1600/Trie4.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;640&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEikwMX3T3ux-bghDQEEgvFkxMf7zjG0lkcFH-EaAthCk7zJwrFAIyTEyBfym18ouiwj4I9u4_LliCGCGWxePJxKI-cn-x-TTnjEPH4GMz5dD1xDZsvafaPTigXXtr9p-SHTu5tuyVasmB0N/s640/Trie4.png&quot; width=&quot;300&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div align=&quot;center&quot;&gt;
﻿&lt;/div&gt;
&lt;ul&gt;
&lt;li&gt;Add &quot;t&quot;.&lt;/li&gt;
&lt;/ul&gt;
&lt;br /&gt;
&lt;div align=&quot;center&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj43L3RM7dOY7tSbjrRduMPGPxdfKi6rmiBdIKMkSJQWMzb5DAdabKaP6-g3n7lXR2kJmcy3p4CcCPi96t7GdbqasbWos0cUpg5XcUfVuvYnTYDzdVQVHa7tMwdbN_NFTTYnvQ0EcS2Y-sr/s1600/Trie5.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;640&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj43L3RM7dOY7tSbjrRduMPGPxdfKi6rmiBdIKMkSJQWMzb5DAdabKaP6-g3n7lXR2kJmcy3p4CcCPi96t7GdbqasbWos0cUpg5XcUfVuvYnTYDzdVQVHa7tMwdbN_NFTTYnvQ0EcS2Y-sr/s640/Trie5.png&quot; width=&quot;378&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div align=&quot;center&quot;&gt;
﻿&lt;/div&gt;
&lt;div align=&quot;center&quot;&gt;
﻿&lt;/div&gt;
&lt;ul&gt;
&lt;li&gt;Add &quot;amy&quot;.&lt;/li&gt;
&lt;/ul&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjPMlqDwT3KNWzIBgbxCcD1JLDB4T4EGmnUPYdiocG-j8bTj5cRf3th3umbfNYFu4by5PzWcO0BZQ22yhoxzne_I3anvjQkRgA7fZJjTwX4SKh1yJ3cU0G-Hiogn5n-CPB-_-N2p8aBDEOH/s1600/Trie6.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;640&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjPMlqDwT3KNWzIBgbxCcD1JLDB4T4EGmnUPYdiocG-j8bTj5cRf3th3umbfNYFu4by5PzWcO0BZQ22yhoxzne_I3anvjQkRgA7fZJjTwX4SKh1yJ3cU0G-Hiogn5n-CPB-_-N2p8aBDEOH/s640/Trie6.png&quot; width=&quot;454&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div align=&quot;center&quot;&gt;
﻿&lt;/div&gt;
&lt;ul&gt;
&lt;li&gt;Add &quot;aramis&quot;.&lt;/li&gt;
&lt;/ul&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi9Ev4hsMXSIX0H1o2eCBv8lRQsnVkRJOH8QVwa_izHZihXrsEYVt_k5vcURb1f4iXwiZIsw1_u-DcUgj4sU7AwzumxDbPq4IbYanm0kj-HoDmm-BzGdJMigchdDMBlYtiFk9T6MNWKIn5W/s1600/Trie7.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;640&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi9Ev4hsMXSIX0H1o2eCBv8lRQsnVkRJOH8QVwa_izHZihXrsEYVt_k5vcURb1f4iXwiZIsw1_u-DcUgj4sU7AwzumxDbPq4IbYanm0kj-HoDmm-BzGdJMigchdDMBlYtiFk9T6MNWKIn5W/s640/Trie7.png&quot; width=&quot;546&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div align=&quot;center&quot;&gt;
﻿&lt;/div&gt;
&lt;br /&gt;
This is the complete Trie with all the entries. Now let us try deleting the names. I am not capturing the trivial cases. &lt;br /&gt;
&lt;br /&gt;
&lt;ul&gt;
&lt;li&gt;Lets try deleting Argo.&lt;/li&gt;
&lt;/ul&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj-kUM7_5-rzI3wxmToOqXJsHqbN1Q2r4BNH1V-tHOfhyphenhyphenJDZeXRBI0lXJwXNm93ofcmAdk3b5OxqjdtCnSLEyjl5PD3l8FeYfBHWexSjQGhJVdHh8HEhJ10kJY1Bd3U-6wzav2gPKW7x-GS/s1600/TrieD1.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;640&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj-kUM7_5-rzI3wxmToOqXJsHqbN1Q2r4BNH1V-tHOfhyphenhyphenJDZeXRBI0lXJwXNm93ofcmAdk3b5OxqjdtCnSLEyjl5PD3l8FeYfBHWexSjQGhJVdHh8HEhJ10kJY1Bd3U-6wzav2gPKW7x-GS/s640/TrieD1.png&quot; width=&quot;548&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div align=&quot;center&quot;&gt;
﻿&lt;/div&gt;
&lt;ul&gt;
&lt;li&gt;Delete Tina&lt;/li&gt;
&lt;/ul&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEizzkmLSOiebTdMjnV-Jc5jy3d96tDzcgD4pbmJRc8hz1kefVrj0nhhgVBC5V0AfeGHAvhErBEPdLEp_uMkc-Pg4jIjw2GHzywIELu5nTx0ocasPOIiNaxJ_O5kpXbQ_kN4xXT9ztH7B14a/s1600/TrieD2.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;640&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEizzkmLSOiebTdMjnV-Jc5jy3d96tDzcgD4pbmJRc8hz1kefVrj0nhhgVBC5V0AfeGHAvhErBEPdLEp_uMkc-Pg4jIjw2GHzywIELu5nTx0ocasPOIiNaxJ_O5kpXbQ_kN4xXT9ztH7B14a/s640/TrieD2.png&quot; width=&quot;548&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div align=&quot;center&quot;&gt;
﻿&lt;/div&gt;
&lt;ul&gt;
&lt;li&gt;Delete Andrew&lt;/li&gt;
&lt;/ul&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjbOG45BzhShzt6yuebNAjj75Ue5QMbqedqiqiBCih7FiOw7hZ6urOgvRaRciLBMPNvSak-52G26VmLogQ_t_vP875j97ckLJdQcp5aqvhxIxrc9Yko5yMUauxbBPUqjdSHayYNBqSV1q0K/s1600/TrieD3.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;640&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjbOG45BzhShzt6yuebNAjj75Ue5QMbqedqiqiBCih7FiOw7hZ6urOgvRaRciLBMPNvSak-52G26VmLogQ_t_vP875j97ckLJdQcp5aqvhxIxrc9Yko5yMUauxbBPUqjdSHayYNBqSV1q0K/s640/TrieD3.png&quot; width=&quot;549&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div align=&quot;center&quot;&gt;
﻿&lt;/div&gt;
&lt;br /&gt;
&lt;br /&gt;
There is also a video from IIT Delhi which explains the tries. &lt;a href=&quot;http://www.youtube.com/watch?v=uhAUk63tLRM&quot; target=&quot;_blank&quot;&gt;Tries Explained&lt;/a&gt;.&lt;br /&gt;
The implementation for this Trie is given below. Please provide your suggestions to further improve the implementation.
&lt;!--pre class=&quot;cpp&quot; name=&quot;code&quot;--&gt;
&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;
&lt;code class=&quot;language-cpp&quot;&gt;/*trie.h*/
typedef int trieVal_t;

typedef struct trieNode {
    char key;
    trieVal_t value;
    struct trieNode *next;
    struct trieNode *prev;
    struct trieNode *children;
    struct trieNode *parent;
} trieNode_t;

void TrieCreate(trieNode_t **root);
trieNode_t* TrieSearch(trieNode_t *root, const char *key);
void TrieAdd(trieNode_t **root, char *key, int data);
void TrieRemove(trieNode_t **root, char *key);
void TrieDestroy( trieNode_t* root );
&lt;/code&gt;
&lt;/pre&gt;

&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;
&lt;code class=&quot;language-cpp&quot;&gt;/*trie.c*/
#include &amp;lt;stdio.h&amp;gt;
#include &quot;trie.h&quot;
#include &amp;lt;stdlib.h&amp;gt;

trieNode_t *TrieCreateNode(char key, int data);

void TrieCreate(trieNode_t **root)
{
 *root = TrieCreateNode(&#39;\0&#39;, 0xffffffff);
}

trieNode_t *TrieCreateNode(char key, int data)
{
 trieNode_t *node = NULL;
 node = (trieNode_t *)malloc(sizeof(trieNode_t));

 if(NULL == node)
 {
  printf(&quot;Malloc failed\n&quot;);
  return node;
 }

 node-&amp;gt;key = key;
 node-&amp;gt;next = NULL;
 node-&amp;gt;children = NULL;
 node-&amp;gt;value = data;
 node-&amp;gt;parent= NULL;
 node-&amp;gt;prev= NULL;
 return node;
}

void TrieAdd(trieNode_t **root, char *key, int data)
{
 trieNode_t *pTrav = NULL;

 if(NULL == *root)
 {
  printf(&quot;NULL tree\n&quot;);
  return;
 }
#ifdef DEBUG
 printf(&quot;\nInserting key %s: \n&quot;,key);
#endif
 pTrav = (*root)-&amp;gt;children;



 if(pTrav == NULL)
 {
  /*First Node*/
  for(pTrav = *root; *key; pTrav = pTrav-&amp;gt;children)
  {
   pTrav-&amp;gt;children = TrieCreateNode(*key, 0xffffffff);
   pTrav-&amp;gt;children-&amp;gt;parent = pTrav;
#ifdef DEBUG
   printf(&quot;Inserting: [%c]\n&quot;,pTrav-&amp;gt;children-&amp;gt;key);
#endif
   key++;
  }

  pTrav-&amp;gt;children = TrieCreateNode(&#39;\0&#39;, data);
  pTrav-&amp;gt;children-&amp;gt;parent = pTrav;
#ifdef DEBUG
  printf(&quot;Inserting: [%c]\n&quot;,pTrav-&amp;gt;children-&amp;gt;key);
#endif
  return;
 }

 if(TrieSearch(pTrav, key))
 {
  printf(&quot;Duplicate!\n&quot;);
  return;
 }

 while(*key != &#39;\0&#39;)
 {
  if(*key == pTrav-&amp;gt;key)
  {
   key++;
#ifdef DEBUG
   printf(&quot;Traversing child: [%c]\n&quot;,pTrav-&amp;gt;children-&amp;gt;key);
#endif
   pTrav = pTrav-&amp;gt;children;
  }
  else
   break;
 }

 while(pTrav-&amp;gt;next)
 {
  if(*key == pTrav-&amp;gt;next-&amp;gt;key)
  {
   key++;
   TrieAdd(&amp;amp;(pTrav-&amp;gt;next), key, data);
   return;
  }
  pTrav = pTrav-&amp;gt;next;
 }

 if(*key)
 {
  pTrav-&amp;gt;next = TrieCreateNode(*key, 0xffffffff);
 }
 else
 {
  pTrav-&amp;gt;next = TrieCreateNode(*key, data);
 }

 pTrav-&amp;gt;next-&amp;gt;parent = pTrav-&amp;gt;parent;
 pTrav-&amp;gt;next-&amp;gt;prev = pTrav;

#ifdef DEBUG
 printf(&quot;Inserting [%c] as neighbour of [%c] \n&quot;,pTrav-&amp;gt;next-&amp;gt;key, pTrav-&amp;gt;key);
#endif

 if(!(*key))
  return;

 key++;

 for(pTrav = pTrav-&amp;gt;next; *key; pTrav = pTrav-&amp;gt;children)
 {
  pTrav-&amp;gt;children = TrieCreateNode(*key, 0xffffffff);
  pTrav-&amp;gt;children-&amp;gt;parent = pTrav;
#ifdef DEBUG
  printf(&quot;Inserting: [%c]\n&quot;,pTrav-&amp;gt;children-&amp;gt;key);
#endif
  key++;
 }

 pTrav-&amp;gt;children = TrieCreateNode(&#39;\0&#39;, data);
 pTrav-&amp;gt;children-&amp;gt;parent = pTrav;
#ifdef DEBUG
 printf(&quot;Inserting: [%c]\n&quot;,pTrav-&amp;gt;children-&amp;gt;key);
#endif
 return;
}

trieNode_t* TrieSearch(trieNode_t *root, const char *key)
{
 trieNode_t *level = root;
 trieNode_t *pPtr = NULL;

 int lvl=0;
 while(1)
 {
  trieNode_t *found = NULL;
  trieNode_t *curr;

  for (curr = level; curr != NULL; curr = curr-&amp;gt;next)
  {
   if (curr-&amp;gt;key == *key)
   {
    found = curr;
    lvl++;
    break;
   }
  }

  if (found == NULL)
   return NULL;

  if (*key == &#39;\0&#39;)
  {
   pPtr = curr;
   return pPtr;
  }

  level = found-&amp;gt;children;
  key++;
 }
}

void TrieRemove(trieNode_t **root, char *key)
{
 trieNode_t *tPtr = NULL;
 trieNode_t *tmp = NULL;

 if(NULL == *root || NULL == key)
  return;

 tPtr = TrieSearch((*root)-&amp;gt;children, key);

 if(NULL == tPtr)
 {
  printf(&quot;Key [%s] not found in trie\n&quot;, key);
  return;
 }

#ifdef DEBUG
 printf(&quot;Deleting key [%s] from trie\n&quot;, key);
#endif

 while(1)
 {
  if( tPtr-&amp;gt;prev &amp;amp;&amp;amp; tPtr-&amp;gt;next)
  {
   tmp = tPtr;
   tPtr-&amp;gt;next-&amp;gt;prev = tPtr-&amp;gt;prev;
   tPtr-&amp;gt;prev-&amp;gt;next = tPtr-&amp;gt;next;
#ifdef DEBUG
   printf(&quot;Deleted [%c] \n&quot;, tmp-&amp;gt;key);
#endif
   free(tmp);
   break;
  }
  else if(tPtr-&amp;gt;prev &amp;amp;&amp;amp; !(tPtr-&amp;gt;next))
  {
   tmp = tPtr;
   tPtr-&amp;gt;prev-&amp;gt;next = NULL;
#ifdef DEBUG
   printf(&quot;Deleted [%c] \n&quot;, tmp-&amp;gt;key);
#endif
   free(tmp);
   break;
  }
  else if(!(tPtr-&amp;gt;prev) &amp;amp;&amp;amp; tPtr-&amp;gt;next)
  {
   tmp = tPtr;
   tPtr-&amp;gt;parent-&amp;gt;children = tPtr-&amp;gt;next;
#ifdef DEBUG
   printf(&quot;Deleted [%c] \n&quot;, tmp-&amp;gt;key);
#endif
   free(tmp);
   break;
  }
  else
  {
   tmp = tPtr;
   tPtr = tPtr-&amp;gt;parent;
   tPtr-&amp;gt;children = NULL;
#ifdef DEBUG
   printf(&quot;Deleted [%c] \n&quot;, tmp-&amp;gt;key);
#endif
   free(tmp);
  }
 }

#ifdef DEBUG
 printf(&quot;Deleted key [%s] from trie\n&quot;, key);
#endif
}


void TrieDestroy( trieNode_t* root )
{
 trieNode_t *tPtr = root;
 trieNode_t *tmp = root;

    while(tPtr)
 {
  while(tPtr-&amp;gt;children)
   tPtr = tPtr-&amp;gt;children;

  if( tPtr-&amp;gt;prev &amp;amp;&amp;amp; tPtr-&amp;gt;next)
  {
   tmp = tPtr;
   tPtr-&amp;gt;next-&amp;gt;prev = tPtr-&amp;gt;prev;
   tPtr-&amp;gt;prev-&amp;gt;next = tPtr-&amp;gt;next;
#ifdef DEBUG
   printf(&quot;Deleted [%c] \n&quot;, tmp-&amp;gt;key);
#endif
   free(tmp);
  }
  else if(tPtr-&amp;gt;prev &amp;amp;&amp;amp; !(tPtr-&amp;gt;next))
  {
   tmp = tPtr;
   tPtr-&amp;gt;prev-&amp;gt;next = NULL;
#ifdef DEBUG
   printf(&quot;Deleted [%c] \n&quot;, tmp-&amp;gt;key);
#endif
   free(tmp);
  }
  else if(!(tPtr-&amp;gt;prev) &amp;amp;&amp;amp; tPtr-&amp;gt;next)
  {
   tmp = tPtr;
   tPtr-&amp;gt;parent-&amp;gt;children = tPtr-&amp;gt;next;
   tPtr-&amp;gt;next-&amp;gt;prev = NULL;
   tPtr = tPtr-&amp;gt;next;
#ifdef DEBUG
   printf(&quot;Deleted [%c] \n&quot;, tmp-&amp;gt;key);
#endif
   free(tmp);
  }
  else
  {
   tmp = tPtr;
   if(tPtr-&amp;gt;parent == NULL)
   {
    /*Root*/
    free(tmp);
    return;
   }
   tPtr = tPtr-&amp;gt;parent;
   tPtr-&amp;gt;children = NULL;
#ifdef DEBUG
   printf(&quot;Deleted [%c] \n&quot;, tmp-&amp;gt;key);
#endif
   free(tmp);
  }
 }

}

&lt;/code&gt;
&lt;/pre&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;
&lt;code class=&quot;language-cpp&quot;&gt;/*triedriver.c*/
/*
 * To Compile : gcc -o trie trie.c triedriver.c
 * To run: ./trie
 */
#include &amp;lt;stdio.h&amp;gt;
#include &amp;lt;stdlib.h&amp;gt;
#include &quot;trie.h&quot;

int main()
{
    trieNode_t *root;
    printf(&quot;Trie Example\n&quot;);
    
    /*Create a trie*/
    TrieCreate(&amp;amp;root);
    
    TrieAdd(&amp;amp;root, &quot;andrew&quot;, 1);
    TrieAdd(&amp;amp;root, &quot;tina&quot;, 2);
    TrieAdd(&amp;amp;root, &quot;argo&quot;, 3);
    TrieAdd(&amp;amp;root, &quot;timor&quot;, 5);
    TrieRemove(&amp;amp;root, &quot;tim&quot;);
    TrieAdd(&amp;amp;root, &quot;tim&quot;, 6);
    TrieRemove(&amp;amp;root, &quot;tim&quot;);
    TrieAdd(&amp;amp;root, &quot;ti&quot;, 6);
    TrieAdd(&amp;amp;root, &quot;amy&quot;, 7);
    TrieAdd(&amp;amp;root, &quot;aramis&quot;, 8);

    /*Destroy the trie*/
    TrieDestroy(root);
}

&lt;/code&gt;
&lt;/pre&gt;
In order to print the debug messages, use -DDEBUG while compiling with gcc:&lt;br /&gt;
&lt;pre class=&quot;brush:cpp&quot;&gt;gcc -o trie trie.c triedriver.c -DDEBUG&lt;/code&gt;
&lt;/pre&gt;

&lt;/div&gt;
</description><link>http://simplestcodings.blogspot.com/2012/11/trie-implementation-in-c.html</link><author>noreply@blogger.com (Anonymous)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgyyoXgdnY_8wmBey5E6MSZ_3CMr5F7AsPOVmIsyl4OMDfxSRNiF21clUJNgcJeFj_ES1lQdSxZjD_UlHPiOITmhZcrPOyTbzm7WgRaCaAxgbhFEho5p4gp1JqAS0-VM-ZxVepMBh18xxak/s72-c/TrieNodes.png" height="72" width="72"/><thr:total>57</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-3459284654925679524.post-1180434876571261370</guid><pubDate>Wed, 31 Oct 2012 14:16:00 +0000</pubDate><atom:updated>2023-12-21T00:13:15.326+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">abstract binary search tree</category><category domain="http://www.blogger.com/atom/ns#">BST</category><category domain="http://www.blogger.com/atom/ns#">C programming</category><category domain="http://www.blogger.com/atom/ns#">Data Structures</category><category domain="http://www.blogger.com/atom/ns#">efficiency</category><category domain="http://www.blogger.com/atom/ns#">search algorithms</category><title>Abstract Binary Search Tree Implementation in C</title><description>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
There are several ways to store data using different data structures like Array, Linked Lists , Trees, Graphs, Hashmaps etc. The choice of the data structure depends on the application which extracts that data. On searching the web , one can easily find out which data structure is required for their application. Binary Search Tree is one such data structure which is generally used for storing data.&lt;br /&gt;
&lt;br /&gt;
A binary search tree consists of members called as nodes which have the data embedded in them. Generally, a BST node contains address fields and data field. The structure of a BST is something like this :&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiYyxJVY1Z16EPtRK1R3aW0Q6hl0sC3hoS9At8kdcfE-OuQXcqvImPv6IIcKvR7kki1ZLMegJoSIPLIHpjzu4bl81qy8Q-dwUqH1z-NXSdH3TlFYqOFuAC3fghjRaGZvMgWYjvGdn767IA/s1600/bst.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;208&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiYyxJVY1Z16EPtRK1R3aW0Q6hl0sC3hoS9At8kdcfE-OuQXcqvImPv6IIcKvR7kki1ZLMegJoSIPLIHpjzu4bl81qy8Q-dwUqH1z-NXSdH3TlFYqOFuAC3fghjRaGZvMgWYjvGdn767IA/s320/bst.png&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
Each node can have a left subtree and right subtree which may or may not have any nodes.&lt;br /&gt;
&lt;br /&gt;
Binary Search tree has some properties which identifies it :&lt;br /&gt;
&lt;br /&gt;
&lt;ul style=&quot;background-color: white; list-style-image: url(data:image/png; list-style-type: square; margin: 0.3em 0px 0px 1.6em; padding: 0px; text-align: -webkit-auto;&quot;&gt;
&lt;li style=&quot;margin-bottom: 0.1em;&quot;&gt;The left subtree members have a value which is always less than the value at the root node&lt;/li&gt;
&lt;li style=&quot;margin-bottom: 0.1em;&quot;&gt;The right subtree members have a value which is always greater than the value at the root node&lt;/li&gt;
&lt;li style=&quot;margin-bottom: 0.1em;&quot;&gt;Both the subtrees must be also a BST.&lt;/li&gt;
&lt;/ul&gt;
&lt;div style=&quot;text-align: -webkit-auto;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div style=&quot;text-align: -webkit-auto;&quot;&gt;
The implementation provided in this post uses an abstract data type (void). To use this implementation as it is, one must implement these two functions&amp;nbsp;&lt;/div&gt;
&lt;div style=&quot;text-align: -webkit-auto;&quot;&gt;
&lt;ol style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;&lt;b&gt;&lt;u&gt;Comparison Function&lt;/u&gt;&lt;/b&gt; - This function compares the data between two nodes. This function must return -1, 0 or 1 only. &amp;nbsp;The signature for this function is&amp;nbsp;&lt;b style=&quot;background-color: white;&quot;&gt;&lt;span style=&quot;color: blue;&quot;&gt;&lt;i&gt;int &amp;lt;function-name&amp;gt; (void * data1, void * data2).&lt;/i&gt;&lt;/span&gt;&lt;/b&gt;&lt;/li&gt;
&lt;ol&gt;
&lt;li&gt;&lt;span style=&quot;background-color: white;&quot;&gt;Function should return 1 when data1 is greater than data2.&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span style=&quot;background-color: white;&quot;&gt;Function should return -1 when data1 is lesser than data2.&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span style=&quot;background-color: white;&quot;&gt;Function should return 0 when data1 is equal to data2. &amp;nbsp;&lt;/span&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;li&gt;&lt;u&gt;&lt;b&gt;Display Function&lt;/b&gt;&lt;/u&gt; - This function is used for display purposes only. It displays the node data.&lt;/li&gt;
&lt;/ol&gt;
&lt;div style=&quot;text-align: left;&quot;&gt;
A sample implementation of these two functions is presented in the driver example(&lt;i&gt;bstdriver.c&lt;/i&gt;) for the BST. This sample implementation uses &lt;i&gt;&lt;b&gt;int&lt;/b&gt; &lt;/i&gt;type as data.&lt;/div&gt;
&lt;div style=&quot;text-align: left;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div style=&quot;text-align: left;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;!--pre class=&quot;cpp&quot; name=&quot;code&quot;--&gt;
&lt;pre class=&quot;prettyprint&quot;&gt; &lt;code class=&quot;language-cpp&quot;&gt;
/*bst.h*/
typedef struct bstNode
{
    struct bstNode *left;       /*Left Child*/
    struct bstNode *right;      /*Right Child*/
    struct bstNode *parent;     /*Parent Child*/
    void *data;                 /*Data*/
}BSTNode;

void BSTDestroy(BSTNode *root);
void BSTInsert(BSTNode **root, void *data, int (*cmp_fn)(void *, void *));
void BSTDelete(BSTNode **root, void *data, int (*cmp_fn)(void *, void *));
BSTNode* BSTSearch(BSTNode *root, void *data, int (*cmp_fn)(void *, void *));
void BSTDisplay(BSTNode *root, void (*display_fn)(BSTNode *));
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;pre class=&quot;prettyprint&quot;&gt; &lt;code class=&quot;language-cpp&quot;&gt;
/*bst.c*/
#include &amp;lt;stdio.h&amp;gt;
#include &amp;lt;stdlib.h&amp;gt;

#include &quot;bst.h&quot;

/* @brief Function to determine if a child is a left child or right child in a BST
 * @param data Pointer to the data to be used
 * @return LEFT - if left child
 *         RIGHT - if right child
 */
static inline const char* BSTFindChildLoc(BSTNode *parent, BSTNode *child)
{
    return (((parent-&amp;gt;left)==(child))?&quot;LEFT&quot;:&quot;RIGHT&quot;);
}

/* @brief Function to swap data between two nodes in a BST
 * @param data Pointer to the data to be used
 * @return void
 */
static inline void BSTSwapNodeData(BSTNode **node1, BSTNode **node2 )
{
    void *tmp;
    tmp = (*node1)-&amp;gt;data;
    (*node1)-&amp;gt;data = (*node2)-&amp;gt;data;
    (*node2)-&amp;gt;data = tmp;
}

/* @brief Function to create a node in a BST
 * @param data Pointer to the data to be used
 * @return Address of the node created
 */
BSTNode* BSTCreateNode(void *data)
{
    /*Allocate memory*/
    BSTNode* node= (BSTNode*)malloc(sizeof(BSTNode));

    if(NULL == node)
    {
        printf(&quot;Error: Memory Allocation could not be completed\n&quot;);
        return NULL;
    }

    /*Initialize links*/
    node-&amp;gt;left = NULL;
    node-&amp;gt;right= NULL;
    node-&amp;gt;parent= NULL;
    node-&amp;gt;data = data;

    printf(&quot;Allocated Node with address %p\n&quot;, node);
    return node;
}

/* @brief Function to destroy all nodes in a BST
 * @param root Pointer to the root of the BST
 * @return void
 */
void BSTDestroy(BSTNode *root)
{
    if(root)
    {
        /*Traverse down the left subtree*/
        if(root-&amp;gt;left)
            BSTDestroy(root-&amp;gt;left);
        /*Traverse down the right subtree*/
        if(root-&amp;gt;right)
            BSTDestroy(root-&amp;gt;right);
        /*Free the memory*/
        free(root);
        printf(&quot;DeAllocated Node with address %p\n&quot;, root);
    }
}

/* @brief Function to insert a node in a BST
 * @param root Pointer to pointer to the root of the BST
 * @param data Pointer to the data to be inserted
 * @param cmp_fn Funtion Pointer to the comparison function for BST[Provided by user]
 * @return void
 */
void BSTInsert(BSTNode **root, void *data, int (*cmp_fn)(void *, void *))
{
    BSTNode *tmp = NULL;
    BSTNode *ptr = NULL;

    if(NULL == root)
    {
        printf(&quot;Error: Null root\n&quot;);
        return;
    }


    if(!(*root))
    {
        /*Create a node*/
        tmp = BSTCreateNode(data);

        if(NULL == tmp)
        {
            printf(&quot;Error: Node insertion failed\n&quot;);
            return;
        }

        /*Root Node*/
        *root = tmp;
        return;
    }

    ptr = *root;

    /*If data is greater than the current node&#39;s data*/
    if(cmp_fn(data,ptr-&amp;gt;data) == 1)
    {
        /*data &amp;gt; ptr-&amp;gt;data : Insert to right*/
        if(ptr-&amp;gt;right == NULL)
        {
            /*Create a node*/
            tmp = BSTCreateNode(data);

            if(NULL == tmp)
            {
                printf(&quot;Error: Node insertion failed\n&quot;);
                return;
            }

            tmp-&amp;gt;parent = ptr;
            ptr-&amp;gt;right = tmp;
            return;
        }
        else
        {
            BSTInsert(&amp;amp;(ptr-&amp;gt;right), data, cmp_fn);
        }
    }
    /*If data is lesser than the current node&#39;s data*/
    else if(cmp_fn(data,ptr-&amp;gt;data) == -1)
    {
        /*data &amp;gt; ptr-&amp;gt;data : Insert to right*/
        if(ptr-&amp;gt;left == NULL)
        {
            tmp = BSTCreateNode(data);

            if(NULL == tmp)
            {
                printf(&quot;Error: Node insertion failed\n&quot;);
                return;
            }

            tmp-&amp;gt;parent = ptr;
            ptr-&amp;gt;left = tmp;
            return;
        }
        else
        {
            BSTInsert(&amp;amp;(ptr-&amp;gt;left), data, cmp_fn);
        }
    }
    /*If data is equal to the current node&#39;s data*/
    else
        printf(&quot;Error: Duplicate\n&quot;);
}

/* @brief Function to find the minimum valued node in the left subtree of a node
 * @param node Pointer to the node whose min valued child in left subtree has to be found
 * @return Address of the minimum valued node in the left subtree
 */
static BSTNode* BSTMinVal(BSTNode* node)
{
    BSTNode* current = node;

  /*Go to the leftmost member of the tree */
  while (current-&amp;gt;left != NULL)
  {
    current = current-&amp;gt;left;
  }
  return current;
}

/* @brief Function to find the Inorder successor of a node in a BST
 * @param node Pointer to the node whose inorder successor has to be found
 * @return Address of the Inorder successor
 */
static BSTNode* BSTInorderSuccessor(BSTNode* node)
{
    BSTNode *inOrdSucc = NULL;
    if(NULL == node)
        return NULL;

    /*Traverse the right subtree and find the minimum value */
    if( node-&amp;gt;right != NULL )
        return BSTMinVal(node-&amp;gt;right);

    inOrdSucc = node-&amp;gt;parent;

    while(inOrdSucc != NULL &amp;amp;&amp;amp; node == inOrdSucc-&amp;gt;right)
    {
        node = inOrdSucc;
        inOrdSucc = inOrdSucc-&amp;gt;parent;
    }
    return inOrdSucc;

}

/* @brief Helper Function to update the parent node links in a BST
 * @param node Pointer to pointer to the node whose parent will be updated
 * @param ptr Target Link
 * @return void
 */
static inline void updateParent(BSTNode **node, BSTNode *ptr)
{
    /*If the child is a left child*/
    if(BSTFindChildLoc((*node)-&amp;gt;parent, *node) == &quot;LEFT&quot;)
    {
        (*node)-&amp;gt;parent-&amp;gt;left = ptr;
    }
    /*If the child is a right child*/
    else
    {
        (*node)-&amp;gt;parent-&amp;gt;right = ptr;
    }
}

/* @brief Function to delete a node in a BST
 * @param root Pointer to pointer to the root of the BST
 * @param data Pointer to the data to be searched
 * @param cmp_fn Funtion Pointer to the comparison function for BST[Provided by user]
 * @return void
 */
void BSTDelete(BSTNode **root, void *data, int (*cmp_fn)(void *, void *))
{
    BSTNode *ptr = NULL;
    BSTNode *tmp = NULL;

    if(NULL == root)
    {
        printf(&quot;Error: Null root\n&quot;);
        return;
    }

    /*Search if the node exists in the BST*/
    ptr = BSTSearch(*root, data, cmp_fn);

    if(NULL == ptr)
    {
        printf(&quot;Error: Node not found\n&quot;);
        return;
    }

    /*If the node has no children*/
    if(ptr-&amp;gt;left == NULL &amp;amp;&amp;amp; ptr-&amp;gt;right == NULL)
    {
        /*No children*/
         tmp = ptr;

         /*Non-Root Node*/
         if(ptr-&amp;gt;parent)
            updateParent(&amp;amp;ptr, NULL);   /*Update the parent&#39;s link*/
         /*Root Node*/
         else
             *root = NULL;

         ptr = NULL;
         free(tmp);
         printf(&quot;DeAllocated Node with address %p\n&quot;, tmp);
    }
    /*If the node has single child*/
    else if((ptr-&amp;gt;left != NULL &amp;amp;&amp;amp; ptr-&amp;gt;right == NULL) || (ptr-&amp;gt;left == NULL &amp;amp;&amp;amp; ptr-&amp;gt;right != NULL))
    {
        tmp = ptr;

        /*Single Child*/
        if((ptr-&amp;gt;left != NULL) &amp;amp;&amp;amp; (ptr-&amp;gt;right == NULL))
        {
            ptr-&amp;gt;left-&amp;gt;parent = ptr-&amp;gt;parent;

            /*Non-Root Node*/
            if(ptr-&amp;gt;parent)
                updateParent(&amp;amp;ptr, ptr-&amp;gt;left);   /*Update the parent&#39;s link*/
            /*Root Node*/
            else
                *root = ptr-&amp;gt;left;
        }
        else
        {
            ptr-&amp;gt;right-&amp;gt;parent = ptr-&amp;gt;parent;   /*Update the parent&#39;s link*/
            /*Non-Root Node*/
            if(ptr-&amp;gt;parent)
                updateParent(&amp;amp;ptr, ptr-&amp;gt;right);
            /*Root Node*/
            else
                *root = ptr-&amp;gt;right;
        }

        free(tmp);
        printf(&quot;DeAllocated Node with address %p\n&quot;, tmp);
    }
    /*If the node has two children*/
    else if((ptr-&amp;gt;left != NULL) &amp;amp;&amp;amp; (ptr-&amp;gt;right != NULL))
    {
        /*Find the inorder successor of the node*/
        BSTNode *inOrdSucc = BSTInorderSuccessor(ptr);

        /*Swap the node&#39;s data with inorder successor&#39;s data*/
        BSTSwapNodeData(&amp;amp;ptr, &amp;amp;inOrdSucc);

        /*Delete the inorder successor node*/
        BSTDelete(&amp;amp;inOrdSucc, data, cmp_fn);
    }
}

/* @brief Function to search a data in a BST
 * @param root Pointer to the root of the BST
 * @param data Pointer to the data to be searched
 * @param cmp_fn Funtion Pointer to the comparison function for BST[Provided by user]
 * @return Address of the node found
 *         NULL if node not found
 */
BSTNode* BSTSearch(BSTNode *root, void *data, int (*cmp_fn)(void *, void *))
{
    BSTNode *ptr = NULL;

    if(NULL == root)
        return NULL;

    ptr = root;

    /*If the data is found*/
    if(cmp_fn(data, ptr-&amp;gt;data) == 0)
    {
        return ptr;
    }
    /*If data is greater than the current node&#39;s data*/
    else if(cmp_fn(data, ptr-&amp;gt;data) == 1)
    {
        return BSTSearch(ptr-&amp;gt;right, data, cmp_fn);
    }
    /*If data is lesser than the current node&#39;s data*/
    else if(cmp_fn(data, ptr-&amp;gt;data) == -1)
    {
        return BSTSearch(ptr-&amp;gt;left, data, cmp_fn);
    }

    return NULL;
}

/* @brief Function to traverse all nodes in a BST in InOrder
 * @param root Pointer to the root of the BST
 * @param display_fn Funtion Pointer to the display function for BST[Provided by user]
 * @return void
 */
static void BSTInOrder(BSTNode *root, void (*display_fn)(BSTNode *))
{
    if(NULL == root)
    {
        printf(&quot;Error: NULL root\n&quot;);
        return;
    }

    if(root-&amp;gt;left)
        BSTInOrder(root-&amp;gt;left, display_fn);

    printf(&quot;[%p]&quot;,root-&amp;gt;data);
    display_fn(root);

    if(root-&amp;gt;right)
        BSTInOrder(root-&amp;gt;right, display_fn);

}

/* @brief Function to traverse all nodes in a BST in PostOrder
 * @param root Pointer to the root of the BST
 * @param display_fn Funtion Pointer to the display function for BST[Provided by user]
 * @return void
 */
static void BSTPostOrder(BSTNode *root, void (*display_fn)(BSTNode *))
{
    if(NULL == root)
    {
        printf(&quot;Error: NULL root\n&quot;);
        return;
    }

    if(root-&amp;gt;left)
        BSTPostOrder(root-&amp;gt;left, display_fn);

    if(root-&amp;gt;right)
        BSTPostOrder(root-&amp;gt;right, display_fn);

    printf(&quot;[%p]&quot;,root-&amp;gt;data);
    display_fn(root);
}

/* @brief Function to traverse all nodes in a BST in PreOrder
 * @param root Pointer to the root of the BST
 * @param display_fn Funtion Pointer to the display function for BST[Provided by user]
 * @return void
 */
static void BSTPreOrder(BSTNode *root, void (*display_fn)(BSTNode *))
{
    if(NULL == root)
    {
        printf(&quot;Error: NULL root\n&quot;);
        return;
    }

    printf(&quot;[%p]&quot;,root-&amp;gt;data);
    display_fn(root);

    if(root-&amp;gt;left)
        BSTPreOrder(root-&amp;gt;left, display_fn);

    if(root-&amp;gt;right)
        BSTPreOrder(root-&amp;gt;right, display_fn);

}

/* @brief Function to display all nodes in a BST
 * @param root Pointer to the root of the BST
 * @param display_fn Funtion Pointer to the display function for BST[Provided by user]
 * @return void
 */
void BSTDisplay(BSTNode *root, void (*display_fn)(BSTNode *))
{
    printf(&quot;InOrder -&amp;gt;&quot;,root-&amp;gt;data);
    BSTInOrder(root,display_fn);
    printf(&quot;\n&quot;,root-&amp;gt;data);

    printf(&quot;PreOrder -&amp;gt;&quot;,root-&amp;gt;data);
    BSTPreOrder(root,display_fn);
    printf(&quot;\n&quot;,root-&amp;gt;data);

    printf(&quot;PostOrder -&amp;gt;&quot;,root-&amp;gt;data);
    BSTPostOrder(root,display_fn);
    printf(&quot;\n&quot;,root-&amp;gt;data);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;pre class=&quot;prettyprint&quot;&gt; &lt;code class=&quot;language-cpp&quot;&gt;
/*bstdriver.c*/
/*
 * Compile: gcc -o test bst.c bstdriver.c
 * Run: ./test
 */
#include &amp;lt;stdio.h&amp;gt;
#include &quot;bst.h&quot;

int data[]={9,1,6,3,8,4,2,5,7};

/*Comparison function*/
int cmp_fn(void *data1, void *data2)
{
    if(*((int*)data1) &amp;gt; *((int*)data2))
        return 1;
    else if(*((int*)data1) &amp;lt; *((int*)data2))
        return -1;
    else
        return 0;
}

/*Display Function*/
static void displayNode(BSTNode *node)
{
    if(node)
        printf(&quot;%d &quot;,*((int*)node-&amp;gt;data));
}

int main()
{
    BSTNode *root = NULL;

    int i,sVal=-1;
    int size = sizeof(data)/sizeof(data[0]);

    for(i=0; i &amp;lt; size; i++)
        BSTInsert(&amp;amp;root, &amp;amp;data[i], cmp_fn);

    BSTDisplay(root, displayNode);

    printf(&quot;Search Value : &quot;);
    scanf(&quot;%d&quot;, &amp;amp;sVal);

    if(NULL == BSTSearch(root, &amp;amp;sVal, cmp_fn))
        printf(&quot;Not Found\n&quot;);
    else
        printf(&quot;Found\n&quot;);

    printf(&quot;Delete Value : &quot;);
    scanf(&quot;%d&quot;, &amp;amp;sVal);
    BSTDelete(&amp;amp;root, &amp;amp;sVal, cmp_fn);
    BSTDisplay(root, displayNode);

    BSTDestroy(root);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;br /&gt;&lt;/div&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
 SyntaxHighlighter.highlight();
&lt;/script&gt;</description><link>http://simplestcodings.blogspot.com/2012/10/abstract-binary-search-tree.html</link><author>noreply@blogger.com (Varun)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiYyxJVY1Z16EPtRK1R3aW0Q6hl0sC3hoS9At8kdcfE-OuQXcqvImPv6IIcKvR7kki1ZLMegJoSIPLIHpjzu4bl81qy8Q-dwUqH1z-NXSdH3TlFYqOFuAC3fghjRaGZvMgWYjvGdn767IA/s72-c/bst.png" height="72" width="72"/><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-3459284654925679524.post-6580887668707344186</guid><pubDate>Sun, 23 Sep 2012 18:31:00 +0000</pubDate><atom:updated>2023-12-21T00:27:43.525+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">File transfer protocol</category><category domain="http://www.blogger.com/atom/ns#">FTP</category><category domain="http://www.blogger.com/atom/ns#">FTP implementation in C</category><title>FTP implementation in C</title><description>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgBF0T31WXW0AKpxMaQfg0FkDLnjBpQOCNUpKuIK_4hswYNROrZUDb6zhHsLFssekSVDvfkTaaJeYM5xHk4trVDG9nhE8qCBt4GQbaPyr2c2bcTPW8lZ8mYsKgX1sfpLQYJr40-IhYowJR6nUt9-95ahynhYaPN3RcxD3bEhKgXZZralcurHfUzb1yYmYY/s1024/ftp.jpeg&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;1024&quot; data-original-width=&quot;1024&quot; height=&quot;320&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgBF0T31WXW0AKpxMaQfg0FkDLnjBpQOCNUpKuIK_4hswYNROrZUDb6zhHsLFssekSVDvfkTaaJeYM5xHk4trVDG9nhE8qCBt4GQbaPyr2c2bcTPW8lZ8mYsKgX1sfpLQYJr40-IhYowJR6nUt9-95ahynhYaPN3RcxD3bEhKgXZZralcurHfUzb1yYmYY/s320/ftp.jpeg&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;&lt;br /&gt;&lt;/div&gt;&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
Most of the beginners would wonder how the known services work. Well this post will give an overview of one of the well-written services in C , the FTP application. I thought that there is no need to re-invent the wheel and use this code as is from Apple&#39;s open source initiative.The code is written in C. &lt;br /&gt;
&lt;br /&gt;&lt;/div&gt;
I am providing the code only for the main file which contains FTP specific functions.
The rest of the supporting files including the Makefile can be downloaded from &lt;a href=&quot;https://docs.google.com/open?id=0B2BScYvBeeu-bU8xbmh5eW5zS2c&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Disclaimer&amp;nbsp;:&lt;/b&gt; This code is taken from&amp;nbsp;&lt;a href=&quot;http://opensource.apple.com/&quot; target=&quot;_blank&quot;&gt;Apple Opensource&lt;/a&gt;&amp;nbsp;. I don&#39;t want Apple to sue me ;)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;


&lt;pre class=&quot;prettyprint&quot;&gt; &lt;code class=&quot;language-cpp&quot;&gt;/*ftp.c*/

/*
 * Copyright (c) 1999 Apple Computer, Inc. All rights reserved.
 *
 * @APPLE_LICENSE_HEADER_START@
 * 
 * &quot;Portions Copyright (c) 1999 Apple Computer, Inc.  All Rights
 * Reserved.  This file contains Original Code and/or Modifications of
 * Original Code as defined in and that are subject to the Apple Public
 * Source License Version 1.0 (the &#39;License&#39;).  You may not use this file
 * except in compliance with the License.  Please obtain a copy of the
 * License at http://www.apple.com/publicsource and read it before using
 * this file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an &#39;AS IS&#39; basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT.  Please see the
 * License for the specific language governing rights and limitations
 * under the License.&quot;
 * 
 * @APPLE_LICENSE_HEADER_END@
 */
/*
 * Copyright (c) 1985, 1989, 1993, 1994
 * The Regents of the University of California.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 * This product includes software developed by the University of
 * California, Berkeley and its contributors.
 * 4. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS&#39;&#39; AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */


#include &amp;lt;sys/param.h&amp;gt;
#include &amp;lt;sys/stat.h&amp;gt;
#include &amp;lt;sys/ioctl.h&amp;gt;
#include &amp;lt;sys/socket.h&amp;gt;
#include &amp;lt;sys/time.h&amp;gt;
#include &amp;lt;sys/file.h&amp;gt;

#include &amp;lt;netinet/in.h&amp;gt;
#include &amp;lt;netinet/in_systm.h&amp;gt;
#include &amp;lt;netinet/ip.h&amp;gt;
#include &amp;lt;arpa/inet.h&amp;gt;
#include &amp;lt;arpa/ftp.h&amp;gt;
#include &amp;lt;arpa/telnet.h&amp;gt;

#include &amp;lt;ctype.h&amp;gt;
#include &amp;lt;err.h&amp;gt;
#include &amp;lt;errno.h&amp;gt;
#include &amp;lt;fcntl.h&amp;gt;
#include &amp;lt;netdb.h&amp;gt;
#include &amp;lt;pwd.h&amp;gt;
#include &amp;lt;signal.h&amp;gt;
#include &amp;lt;stdio.h&amp;gt;
#include &amp;lt;stdlib.h&amp;gt;
#include &amp;lt;string.h&amp;gt;
#include &amp;lt;unistd.h&amp;gt;
#include &amp;lt;stdarg.h&amp;gt;

#include &quot;ftp_var.h&quot;

extern int h_errno;

struct sockaddr_in hisctladdr;
struct sockaddr_in data_addr;
int data = -1;
int abrtflag = 0;
jmp_buf ptabort;
int ptabflg;
int ptflag = 0;
struct sockaddr_in myctladdr;
off_t restart_point = 0;

FILE *cin, *cout;

char *
hookup(host, port)
 char *host;
 int port;
{
 struct hostent *hp = 0;
 int s, len, tos;
 static char hostnamebuf[80];

 memset((char *)&amp;amp;hisctladdr, 0, sizeof (hisctladdr));
 hisctladdr.sin_addr.s_addr = inet_addr(host);
 if (hisctladdr.sin_addr.s_addr != -1) {
  hisctladdr.sin_family = AF_INET;
  (void) strncpy(hostnamebuf, host, sizeof(hostnamebuf));
 } else {
  hp = gethostbyname(host);
  if (hp == NULL) {
   warnx(&quot;%s: %s&quot;, host, hstrerror(h_errno));
   code = -1;
   return ((char *) 0);
  }
  hisctladdr.sin_family = hp-&amp;gt;h_addrtype;
  memmove((caddr_t)&amp;amp;hisctladdr.sin_addr,
    hp-&amp;gt;h_addr_list[0], hp-&amp;gt;h_length);
  (void) strncpy(hostnamebuf, hp-&amp;gt;h_name, sizeof(hostnamebuf));
 }
 hostname = hostnamebuf;
 s = socket(hisctladdr.sin_family, SOCK_STREAM, 0);
 if (s &amp;lt; 0) {
  warn(&quot;socket&quot;);
  code = -1;
  return (0);
 }
 hisctladdr.sin_port = port;
 while (connect(s, (struct sockaddr *)&amp;amp;hisctladdr, sizeof (hisctladdr)) &amp;lt; 0) {
  if (hp &amp;amp;&amp;amp; hp-&amp;gt;h_addr_list[1]) {
   int oerrno = errno;
   char *ia;

   ia = inet_ntoa(hisctladdr.sin_addr);
   errno = oerrno;
   warn(&quot;connect to address %s&quot;, ia);
   hp-&amp;gt;h_addr_list++;
   memmove((caddr_t)&amp;amp;hisctladdr.sin_addr,
     hp-&amp;gt;h_addr_list[0], hp-&amp;gt;h_length);
   fprintf(stdout, &quot;Trying %s...\n&quot;,
    inet_ntoa(hisctladdr.sin_addr));
   (void) close(s);
   s = socket(hisctladdr.sin_family, SOCK_STREAM, 0);
   if (s &amp;lt; 0) {
    warn(&quot;socket&quot;);
    code = -1;
    return (0);
   }
   continue;
  }
  warn(&quot;connect&quot;);
  code = -1;
  goto bad;
 }
 len = sizeof (myctladdr);
 if (getsockname(s, (struct sockaddr *)&amp;amp;myctladdr, &amp;amp;len) &amp;lt; 0) {
  warn(&quot;getsockname&quot;);
  code = -1;
  goto bad;
 }
#ifdef IP_TOS
 tos = IPTOS_LOWDELAY;
 if (setsockopt(s, IPPROTO_IP, IP_TOS, (char *)&amp;amp;tos, sizeof(int)) &amp;lt; 0)
  warn(&quot;setsockopt TOS (ignored)&quot;);
#endif
 cin = fdopen(s, &quot;r&quot;);
 cout = fdopen(s, &quot;w&quot;);
 if (cin == NULL || cout == NULL) {
  warnx(&quot;fdopen failed.&quot;);
  if (cin)
   (void) fclose(cin);
  if (cout)
   (void) fclose(cout);
  code = -1;
  goto bad;
 }
 if (verbose)
  printf(&quot;Connected to %s.\n&quot;, hostname);
 if (getreply(0) &amp;gt; 2) {  /* read startup message from server */
  if (cin)
   (void) fclose(cin);
  if (cout)
   (void) fclose(cout);
  code = -1;
  goto bad;
 }
#ifdef SO_OOBINLINE
 {
 int on = 1;

 if (setsockopt(s, SOL_SOCKET, SO_OOBINLINE, (char *)&amp;amp;on, sizeof(on))
  &amp;lt; 0 &amp;amp;&amp;amp; debug) {
   warn(&quot;setsockopt&quot;);
  }
 }
#endif /* SO_OOBINLINE */

 return (hostname);
bad:
 (void) close(s);
 return ((char *)0);
}

int
login(host)
 char *host;
{
 char tmp[80];
 char *user, *pass, *acct;
 int n, aflag = 0;

 user = pass = acct = 0;
 if (ruserpass(host, &amp;amp;user, &amp;amp;pass, &amp;amp;acct) &amp;lt; 0) {
  code = -1;
  return (0);
 }
 while (user == NULL) {
  char *myname = getlogin();

  if (myname == NULL) {
   struct passwd *pp = getpwuid(getuid());

   if (pp != NULL)
    myname = pp-&amp;gt;pw_name;
  }
  if (myname)
   printf(&quot;Name (%s:%s): &quot;, host, myname);
  else
   printf(&quot;Name (%s): &quot;, host);
  (void) fgets(tmp, sizeof(tmp) - 1, stdin);
  tmp[strlen(tmp) - 1] = &#39;\0&#39;;
  if (*tmp == &#39;\0&#39;)
   user = myname;
  else
   user = tmp;
 }
 n = command(&quot;USER %s&quot;, user);
 if (n == CONTINUE) {
  if (pass == NULL)
   pass = getpass(&quot;Password:&quot;);
  n = command(&quot;PASS %s&quot;, pass);
 }
 if (n == CONTINUE) {
  aflag++;
  acct = getpass(&quot;Account:&quot;);
  n = command(&quot;ACCT %s&quot;, acct);
 }
 if (n != COMPLETE) {
  warnx(&quot;Login failed.&quot;);
  return (0);
 }
 if (!aflag &amp;amp;&amp;amp; acct != NULL)
  (void) command(&quot;ACCT %s&quot;, acct);
 if (proxy)
  return (1);
 for (n = 0; n &amp;lt; macnum; ++n) {
  if (!strcmp(&quot;init&quot;, macros[n].mac_name)) {
   (void) strcpy(line, &quot;$init&quot;);
   makeargv();
   domacro(margc, margv);
   break;
  }
 }
 return (1);
}

void
cmdabort()
{

 printf(&quot;\n&quot;);
 (void) fflush(stdout);
 abrtflag++;
 if (ptflag)
  longjmp(ptabort,1);
}

int command(const char *fmt, ...)
{
 va_list ap;
 int r;
 sig_t oldintr;

 abrtflag = 0;
 if (debug) {
  printf(&quot;---&amp;gt; &quot;);
  va_start(ap, fmt);
  if (strncmp(&quot;PASS &quot;, fmt, 5) == 0)
   printf(&quot;PASS XXXX&quot;);
  else 
   vfprintf(stdout, fmt, ap);
  va_end(ap);
  printf(&quot;\n&quot;);
  (void) fflush(stdout);
 }
 if (cout == NULL) {
  warn(&quot;No control connection for command&quot;);
  code = -1;
  return (0);
 }
 oldintr = signal(SIGINT, cmdabort);
 va_start(ap, fmt);
 vfprintf(cout, fmt, ap);
 va_end(ap);
 fprintf(cout, &quot;\r\n&quot;);
 (void) fflush(cout);
 cpend = 1;
 r = getreply(!strcmp(fmt, &quot;QUIT&quot;));
 if (abrtflag &amp;amp;&amp;amp; oldintr != SIG_IGN)
  (*oldintr)(SIGINT);
 (void) signal(SIGINT, oldintr);
 return (r);
}

char reply_string[BUFSIZ];  /* last line of previous reply */

int
getreply(expecteof)
 int expecteof;
{
 int c, n;
 int dig;
 int originalcode = 0, continuation = 0;
 sig_t oldintr;
 int pflag = 0;
 char *cp, *pt = pasv;

 oldintr = signal(SIGINT, cmdabort);
 for (;;) {
  dig = n = code = 0;
  cp = reply_string;
  while ((c = getc(cin)) != &#39;\n&#39;) {
   if (c == IAC) {     /* handle telnet commands */
    switch (c = getc(cin)) {
    case WILL:
    case WONT:
     c = getc(cin);
     fprintf(cout, &quot;%c%c%c&quot;, IAC, DONT, c);
     (void) fflush(cout);
     break;
    case DO:
    case DONT:
     c = getc(cin);
     fprintf(cout, &quot;%c%c%c&quot;, IAC, WONT, c);
     (void) fflush(cout);
     break;
    default:
     break;
    }
    continue;
   }
   dig++;
   if (c == EOF) {
    if (expecteof) {
     (void) signal(SIGINT,oldintr);
     code = 221;
     return (0);
    }
    lostpeer();
    if (verbose) {
     printf(&quot;421 Service not available, remote server has closed connection\n&quot;);
     (void) fflush(stdout);
    }
    code = 421;
    return (4);
   }
   if (c != &#39;\r&#39; &amp;amp;&amp;amp; (verbose &amp;gt; 0 ||
       (verbose &amp;gt; -1 &amp;amp;&amp;amp; n == &#39;5&#39; &amp;amp;&amp;amp; dig &amp;gt; 4))) {
    if (proxflag &amp;amp;&amp;amp;
       (dig == 1 || dig == 5 &amp;amp;&amp;amp; verbose == 0))
     printf(&quot;%s:&quot;,hostname);
    (void) putchar(c);
   }
   if (dig &amp;lt; 4 &amp;amp;&amp;amp; isdigit(c))
    code = code * 10 + (c - &#39;0&#39;);
   if (!pflag &amp;amp;&amp;amp; code == 227)
    pflag = 1;
   if (dig &amp;gt; 4 &amp;amp;&amp;amp; pflag == 1 &amp;amp;&amp;amp; isdigit(c))
    pflag = 2;
   if (pflag == 2) {
    if (c != &#39;\r&#39; &amp;amp;&amp;amp; c != &#39;)&#39;)
     *pt++ = c;
    else {
     *pt = &#39;\0&#39;;
     pflag = 3;
    }
   }
   if (dig == 4 &amp;amp;&amp;amp; c == &#39;-&#39;) {
    if (continuation)
     code = 0;
    continuation++;
   }
   if (n == 0)
    n = c;
   if (cp &amp;lt; &amp;amp;reply_string[sizeof(reply_string) - 1])
    *cp++ = c;
  }
  if (verbose &amp;gt; 0 || verbose &amp;gt; -1 &amp;amp;&amp;amp; n == &#39;5&#39;) {
   (void) putchar(c);
   (void) fflush (stdout);
  }
  if (continuation &amp;amp;&amp;amp; code != originalcode) {
   if (originalcode == 0)
    originalcode = code;
   continue;
  }
  *cp = &#39;\0&#39;;
  if (n != &#39;1&#39;)
   cpend = 0;
  (void) signal(SIGINT,oldintr);
  if (code == 421 || originalcode == 421)
   lostpeer();
  if (abrtflag &amp;amp;&amp;amp; oldintr != cmdabort &amp;amp;&amp;amp; oldintr != SIG_IGN)
   (*oldintr)(SIGINT);
  return (n - &#39;0&#39;);
 }
}

int
empty(mask, sec)
 struct fd_set *mask;
 int sec;
{
 struct timeval t;

 t.tv_sec = (long) sec;
 t.tv_usec = 0;
 return (select(32, mask, (struct fd_set *) 0, (struct fd_set *) 0, &amp;amp;t));
}

jmp_buf sendabort;

void
abortsend()
{

 mflag = 0;
 abrtflag = 0;
 printf(&quot;\nsend aborted\nwaiting for remote to finish abort\n&quot;);
 (void) fflush(stdout);
 longjmp(sendabort, 1);
}

#define HASHBYTES 1024

void
sendrequest(cmd, local, remote, printnames)
 char *cmd, *local, *remote;
 int printnames;
{
 struct stat st;
 struct timeval start, stop;
 int c, d;
 FILE *fin, *dout = 0, *popen();
 int (*closefunc) __P((FILE *));
 sig_t oldintr, oldintp;
 long bytes = 0, hashbytes = HASHBYTES;
 char *lmode, buf[BUFSIZ], *bufp;

 if (verbose &amp;amp;&amp;amp; printnames) {
  if (local &amp;amp;&amp;amp; *local != &#39;-&#39;)
   printf(&quot;local: %s &quot;, local);
  if (remote)
   printf(&quot;remote: %s\n&quot;, remote);
 }
 if (proxy) {
  proxtrans(cmd, local, remote);
  return;
 }
 if (curtype != type)
  changetype(type, 0);
 closefunc = NULL;
 oldintr = NULL;
 oldintp = NULL;
 lmode = &quot;w&quot;;
 if (setjmp(sendabort)) {
  while (cpend) {
   (void) getreply(0);
  }
  if (data &amp;gt;= 0) {
   (void) close(data);
   data = -1;
  }
  if (oldintr)
   (void) signal(SIGINT,oldintr);
  if (oldintp)
   (void) signal(SIGPIPE,oldintp);
  code = -1;
  return;
 }
 oldintr = signal(SIGINT, abortsend);
 if (strcmp(local, &quot;-&quot;) == 0)
  fin = stdin;
 else if (*local == &#39;|&#39;) {
  oldintp = signal(SIGPIPE,SIG_IGN);
  fin = popen(local + 1, &quot;r&quot;);
  if (fin == NULL) {
   warn(&quot;%s&quot;, local + 1);
   (void) signal(SIGINT, oldintr);
   (void) signal(SIGPIPE, oldintp);
   code = -1;
   return;
  }
  closefunc = pclose;
 } else {
  fin = fopen(local, &quot;r&quot;);
  if (fin == NULL) {
   warn(&quot;local: %s&quot;, local);
   (void) signal(SIGINT, oldintr);
   code = -1;
   return;
  }
  closefunc = fclose;
  if (fstat(fileno(fin), &amp;amp;st) &amp;lt; 0 ||
      (st.st_mode&amp;amp;S_IFMT) != S_IFREG) {
   fprintf(stdout, &quot;%s: not a plain file.\n&quot;, local);
   (void) signal(SIGINT, oldintr);
   fclose(fin);
   code = -1;
   return;
  }
 }
 if (initconn()) {
  (void) signal(SIGINT, oldintr);
  if (oldintp)
   (void) signal(SIGPIPE, oldintp);
  code = -1;
  if (closefunc != NULL)
   (*closefunc)(fin);
  return;
 }
 if (setjmp(sendabort))
  goto abort;

 if (restart_point &amp;amp;&amp;amp;
     (strcmp(cmd, &quot;STOR&quot;) == 0 || strcmp(cmd, &quot;APPE&quot;) == 0)) {
  int rc;

  switch (curtype) {
  case TYPE_A:
   rc = fseek(fin, (long) restart_point, SEEK_SET);
   break;
  case TYPE_I:
  case TYPE_L:
   rc = lseek(fileno(fin), restart_point, SEEK_SET);
   break;
  }
  if (rc &amp;lt; 0) {
   warn(&quot;local: %s&quot;, local);
   restart_point = 0;
   if (closefunc != NULL)
    (*closefunc)(fin);
   return;
  }
  if (command(&quot;REST %ld&quot;, (long) restart_point)
   != CONTINUE) {
   restart_point = 0;
   if (closefunc != NULL)
    (*closefunc)(fin);
   return;
  }
  restart_point = 0;
  lmode = &quot;r+w&quot;;
 }
 if (remote) {
  if (command(&quot;%s %s&quot;, cmd, remote) != PRELIM) {
   (void) signal(SIGINT, oldintr);
   if (oldintp)
    (void) signal(SIGPIPE, oldintp);
   if (closefunc != NULL)
    (*closefunc)(fin);
   return;
  }
 } else
  if (command(&quot;%s&quot;, cmd) != PRELIM) {
   (void) signal(SIGINT, oldintr);
   if (oldintp)
    (void) signal(SIGPIPE, oldintp);
   if (closefunc != NULL)
    (*closefunc)(fin);
   return;
  }
 dout = dataconn(lmode);
 if (dout == NULL)
  goto abort;
 (void) gettimeofday(&amp;amp;start, (struct timezone *)0);
 oldintp = signal(SIGPIPE, SIG_IGN);
 switch (curtype) {

 case TYPE_I:
 case TYPE_L:
  errno = d = 0;
  while ((c = read(fileno(fin), buf, sizeof (buf))) &amp;gt; 0) {
   bytes += c;
   for (bufp = buf; c &amp;gt; 0; c -= d, bufp += d)
    if ((d = write(fileno(dout), bufp, c)) &amp;lt;= 0)
     break;
   if (hash) {
    while (bytes &amp;gt;= hashbytes) {
     (void) putchar(&#39;#&#39;);
     hashbytes += HASHBYTES;
    }
    (void) fflush(stdout);
   }
  }
  if (hash &amp;amp;&amp;amp; bytes &amp;gt; 0) {
   if (bytes &amp;lt; HASHBYTES)
    (void) putchar(&#39;#&#39;);
   (void) putchar(&#39;\n&#39;);
   (void) fflush(stdout);
  }
  if (c &amp;lt; 0)
   warn(&quot;local: %s&quot;, local);
  if (d &amp;lt; 0) {
   if (errno != EPIPE) 
    warn(&quot;netout&quot;);
   bytes = -1;
  }
  break;

 case TYPE_A:
  while ((c = getc(fin)) != EOF) {
   if (c == &#39;\n&#39;) {
    while (hash &amp;amp;&amp;amp; (bytes &amp;gt;= hashbytes)) {
     (void) putchar(&#39;#&#39;);
     (void) fflush(stdout);
     hashbytes += HASHBYTES;
    }
    if (ferror(dout))
     break;
    (void) putc(&#39;\r&#39;, dout);
    bytes++;
   }
   (void) putc(c, dout);
   bytes++;
 /*  if (c == &#39;\r&#39;) {      */
 /*  (void) putc(&#39;\0&#39;, dout);  // this violates rfc */
 /*   bytes++;    */
 /*  }                             */ 
  }
  if (hash) {
   if (bytes &amp;lt; hashbytes)
    (void) putchar(&#39;#&#39;);
   (void) putchar(&#39;\n&#39;);
   (void) fflush(stdout);
  }
  if (ferror(fin))
   warn(&quot;local: %s&quot;, local);
  if (ferror(dout)) {
   if (errno != EPIPE)
    warn(&quot;netout&quot;);
   bytes = -1;
  }
  break;
 }
 if (closefunc != NULL)
  (*closefunc)(fin);
 (void) fclose(dout);
 (void) gettimeofday(&amp;amp;stop, (struct timezone *)0);
 (void) getreply(0);
 (void) signal(SIGINT, oldintr);
 if (oldintp)
  (void) signal(SIGPIPE, oldintp);
 if (bytes &amp;gt; 0)
  ptransfer(&quot;sent&quot;, bytes, &amp;amp;start, &amp;amp;stop);
 return;
abort:
 (void) signal(SIGINT, oldintr);
 if (oldintp)
  (void) signal(SIGPIPE, oldintp);
 if (!cpend) {
  code = -1;
  return;
 }
 if (data &amp;gt;= 0) {
  (void) close(data);
  data = -1;
 }
 if (dout)
  (void) fclose(dout);
 (void) getreply(0);
 code = -1;
 if (closefunc != NULL &amp;amp;&amp;amp; fin != NULL)
  (*closefunc)(fin);
 (void) gettimeofday(&amp;amp;stop, (struct timezone *)0);
 if (bytes &amp;gt; 0)
  ptransfer(&quot;sent&quot;, bytes, &amp;amp;start, &amp;amp;stop);
}

jmp_buf recvabort;

void
abortrecv()
{

 mflag = 0;
 abrtflag = 0;
 printf(&quot;\nreceive aborted\nwaiting for remote to finish abort\n&quot;);
 (void) fflush(stdout);
 longjmp(recvabort, 1);
}

void
recvrequest(cmd, local, remote, lmode, printnames)
 char *cmd, *local, *remote, *lmode;
 int printnames;
{
 FILE *fout, *din = 0;
 int (*closefunc) __P((FILE *));
 sig_t oldintr, oldintp;
 int c, d, is_retr, tcrflag, bare_lfs = 0;
 static int bufsize;
 static char *buf;
 long bytes = 0, hashbytes = HASHBYTES;
 struct timeval start, stop;
 struct stat st;

 is_retr = strcmp(cmd, &quot;RETR&quot;) == 0;
 if (is_retr &amp;amp;&amp;amp; verbose &amp;amp;&amp;amp; printnames) {
  if (local &amp;amp;&amp;amp; *local != &#39;-&#39;)
   printf(&quot;local: %s &quot;, local);
  if (remote)
   printf(&quot;remote: %s\n&quot;, remote);
 }
 if (proxy &amp;amp;&amp;amp; is_retr) {
  proxtrans(cmd, local, remote);
  return;
 }
 closefunc = NULL;
 oldintr = NULL;
 oldintp = NULL;
 tcrflag = !crflag &amp;amp;&amp;amp; is_retr;
 if (setjmp(recvabort)) {
  while (cpend) {
   (void) getreply(0);
  }
  if (data &amp;gt;= 0) {
   (void) close(data);
   data = -1;
  }
  if (oldintr)
   (void) signal(SIGINT, oldintr);
  code = -1;
  return;
 }
 oldintr = signal(SIGINT, abortrecv);
 if (strcmp(local, &quot;-&quot;) &amp;amp;&amp;amp; *local != &#39;|&#39;) {
  if (access(local, 2) &amp;lt; 0) {
   char *dir = strrchr(local, &#39;/&#39;);

   if (errno != ENOENT &amp;amp;&amp;amp; errno != EACCES) {
    warn(&quot;local: %s&quot;, local);
    (void) signal(SIGINT, oldintr);
    code = -1;
    return;
   }
   if (dir != NULL)
    *dir = 0;
   d = access(dir ? local : &quot;.&quot;, 2);
   if (dir != NULL)
    *dir = &#39;/&#39;;
   if (d &amp;lt; 0) {
    warn(&quot;local: %s&quot;, local);
    (void) signal(SIGINT, oldintr);
    code = -1;
    return;
   }
   if (!runique &amp;amp;&amp;amp; errno == EACCES &amp;amp;&amp;amp;
       chmod(local, 0600) &amp;lt; 0) {
    warn(&quot;local: %s&quot;, local);
    (void) signal(SIGINT, oldintr);
    (void) signal(SIGINT, oldintr);
    code = -1;
    return;
   }
   if (runique &amp;amp;&amp;amp; errno == EACCES &amp;amp;&amp;amp;
      (local = gunique(local)) == NULL) {
    (void) signal(SIGINT, oldintr);
    code = -1;
    return;
   }
  }
  else if (runique &amp;amp;&amp;amp; (local = gunique(local)) == NULL) {
   (void) signal(SIGINT, oldintr);
   code = -1;
   return;
  }
 }
 if (!is_retr) {
  if (curtype != TYPE_A)
   changetype(TYPE_A, 0);
 } else if (curtype != type)
  changetype(type, 0);
 if (initconn()) {
  (void) signal(SIGINT, oldintr);
  code = -1;
  return;
 }
 if (setjmp(recvabort))
  goto abort;
 if (is_retr &amp;amp;&amp;amp; restart_point &amp;amp;&amp;amp;
     command(&quot;REST %ld&quot;, (long) restart_point) != CONTINUE)
  return;
 if (remote) {
  if (command(&quot;%s %s&quot;, cmd, remote) != PRELIM) {
   (void) signal(SIGINT, oldintr);
   return;
  }
 } else {
  if (command(&quot;%s&quot;, cmd) != PRELIM) {
   (void) signal(SIGINT, oldintr);
   return;
  }
 }
 din = dataconn(&quot;r&quot;);
 if (din == NULL)
  goto abort;
 if (strcmp(local, &quot;-&quot;) == 0)
  fout = stdout;
 else if (*local == &#39;|&#39;) {
  oldintp = signal(SIGPIPE, SIG_IGN);
  fout = popen(local + 1, &quot;w&quot;);
  if (fout == NULL) {
   warn(&quot;%s&quot;, local+1);
   goto abort;
  }
  closefunc = pclose;
 } else {
  fout = fopen(local, lmode);
  if (fout == NULL) {
   warn(&quot;local: %s&quot;, local);
   goto abort;
  }
  closefunc = fclose;
 }
 if (fstat(fileno(fout), &amp;amp;st) &amp;lt; 0 || st.st_blksize == 0)
  st.st_blksize = BUFSIZ;
 if (st.st_blksize &amp;gt; bufsize) {
  if (buf)
   (void) free(buf);
  buf = malloc((unsigned)st.st_blksize);
  if (buf == NULL) {
   warn(&quot;malloc&quot;);
   bufsize = 0;
   goto abort;
  }
  bufsize = st.st_blksize;
 }
 (void) gettimeofday(&amp;amp;start, (struct timezone *)0);
 switch (curtype) {

 case TYPE_I:
 case TYPE_L:
  if (restart_point &amp;amp;&amp;amp;
      lseek(fileno(fout), restart_point, SEEK_SET) &amp;lt; 0) {
   warn(&quot;local: %s&quot;, local);
   if (closefunc != NULL)
    (*closefunc)(fout);
   return;
  }
  errno = d = 0;
  while ((c = read(fileno(din), buf, bufsize)) &amp;gt; 0) {
   if ((d = write(fileno(fout), buf, c)) != c)
    break;
   bytes += c;
   if (hash) {
    while (bytes &amp;gt;= hashbytes) {
     (void) putchar(&#39;#&#39;);
     hashbytes += HASHBYTES;
    }
    (void) fflush(stdout);
   }
  }
  if (hash &amp;amp;&amp;amp; bytes &amp;gt; 0) {
   if (bytes &amp;lt; HASHBYTES)
    (void) putchar(&#39;#&#39;);
   (void) putchar(&#39;\n&#39;);
   (void) fflush(stdout);
  }
  if (c &amp;lt; 0) {
   if (errno != EPIPE)
    warn(&quot;netin&quot;);
   bytes = -1;
  }
  if (d &amp;lt; c) {
   if (d &amp;lt; 0)
    warn(&quot;local: %s&quot;, local);
   else
    warnx(&quot;%s: short write&quot;, local);
  }
  break;

 case TYPE_A:
  if (restart_point) {
   int i, n, ch;

   if (fseek(fout, 0L, SEEK_SET) &amp;lt; 0)
    goto done;
   n = restart_point;
   for (i = 0; i++ &amp;lt; n;) {
    if ((ch = getc(fout)) == EOF)
     goto done;
    if (ch == &#39;\n&#39;)
     i++;
   }
   if (fseek(fout, 0L, SEEK_CUR) &amp;lt; 0) {
done:
    warn(&quot;local: %s&quot;, local);
    if (closefunc != NULL)
     (*closefunc)(fout);
    return;
   }
  }
  while ((c = getc(din)) != EOF) {
   if (c == &#39;\n&#39;)
    bare_lfs++;
   while (c == &#39;\r&#39;) {
    while (hash &amp;amp;&amp;amp; (bytes &amp;gt;= hashbytes)) {
     (void) putchar(&#39;#&#39;);
     (void) fflush(stdout);
     hashbytes += HASHBYTES;
    }
    bytes++;
    if ((c = getc(din)) != &#39;\n&#39; || tcrflag) {
     if (ferror(fout))
      goto break2;
     (void) putc(&#39;\r&#39;, fout);
     if (c == &#39;\0&#39;) {
      bytes++;
      goto contin2;
     }
     if (c == EOF)
      goto contin2;
    }
   }
   (void) putc(c, fout);
   bytes++;
 contin2: ;
  }
break2:
  if (bare_lfs) {
   printf(&quot;WARNING! %d bare linefeeds received in ASCII mode\n&quot;, bare_lfs);
   printf(&quot;File may not have transferred correctly.\n&quot;);
  }
  if (hash) {
   if (bytes &amp;lt; hashbytes)
    (void) putchar(&#39;#&#39;);
   (void) putchar(&#39;\n&#39;);
   (void) fflush(stdout);
  }
  if (ferror(din)) {
   if (errno != EPIPE)
    warn(&quot;netin&quot;);
   bytes = -1;
  }
  if (ferror(fout))
   warn(&quot;local: %s&quot;, local);
  break;
 }
 if (closefunc != NULL)
  (*closefunc)(fout);
 (void) signal(SIGINT, oldintr);
 if (oldintp)
  (void) signal(SIGPIPE, oldintp);
 (void) fclose(din);
 (void) gettimeofday(&amp;amp;stop, (struct timezone *)0);
 (void) getreply(0);
 if (bytes &amp;gt; 0 &amp;amp;&amp;amp; is_retr)
  ptransfer(&quot;received&quot;, bytes, &amp;amp;start, &amp;amp;stop);
 return;
abort:

/* abort using RFC959 recommended IP,SYNC sequence  */

 if (oldintp)
  (void) signal(SIGPIPE, oldintr);
 (void) signal(SIGINT, SIG_IGN);
 if (!cpend) {
  code = -1;
  (void) signal(SIGINT, oldintr);
  return;
 }

 abort_remote(din);
 code = -1;
 if (data &amp;gt;= 0) {
  (void) close(data);
  data = -1;
 }
 if (closefunc != NULL &amp;amp;&amp;amp; fout != NULL)
  (*closefunc)(fout);
 if (din)
  (void) fclose(din);
 (void) gettimeofday(&amp;amp;stop, (struct timezone *)0);
 if (bytes &amp;gt; 0)
  ptransfer(&quot;received&quot;, bytes, &amp;amp;start, &amp;amp;stop);
 (void) signal(SIGINT, oldintr);
}

/*
 * Need to start a listen on the data channel before we send the command,
 * otherwise the server&#39;s connect may fail.
 */
int
initconn()
{
 char *p, *a;
 int result, len, tmpno = 0;
 int on = 1;
 int a0, a1, a2, a3, p0, p1;

 if (passivemode) {
  data = socket(AF_INET, SOCK_STREAM, 0);
  if (data &amp;lt; 0) {
   perror(&quot;ftp: socket&quot;);
   return(1);
  }
  if ((options &amp;amp; SO_DEBUG) &amp;amp;&amp;amp;
      setsockopt(data, SOL_SOCKET, SO_DEBUG, (char *)&amp;amp;on,
          sizeof (on)) &amp;lt; 0)
   perror(&quot;ftp: setsockopt (ignored)&quot;);
  if (command(&quot;PASV&quot;) != COMPLETE) {
   printf(&quot;Passive mode refused.\n&quot;);
   goto bad;
  }

  /*
   * What we&#39;ve got at this point is a string of comma
   * separated one-byte unsigned integer values.
   * The first four are the an IP address. The fifth is
   * the MSB of the port number, the sixth is the LSB.
   * From that we&#39;ll prepare a sockaddr_in.
   */

  if (sscanf(pasv,&quot;%d,%d,%d,%d,%d,%d&quot;,
      &amp;amp;a0, &amp;amp;a1, &amp;amp;a2, &amp;amp;a3, &amp;amp;p0, &amp;amp;p1) != 6) {
   printf(&quot;Passive mode address scan failure. &quot;
          &quot;Shouldn&#39;t happen!\n&quot;);
   goto bad;
  }

  bzero(&amp;amp;data_addr, sizeof(data_addr));
  data_addr.sin_family = AF_INET;
  a = (char *)&amp;amp;data_addr.sin_addr.s_addr;
  a[0] = a0 &amp;amp; 0xff;
  a[1] = a1 &amp;amp; 0xff;
  a[2] = a2 &amp;amp; 0xff;
  a[3] = a3 &amp;amp; 0xff;
  p = (char *)&amp;amp;data_addr.sin_port;
  p[0] = p0 &amp;amp; 0xff;
  p[1] = p1 &amp;amp; 0xff;

  if (connect(data, (struct sockaddr *)&amp;amp;data_addr,
       sizeof(data_addr)) &amp;lt; 0) {
   perror(&quot;ftp: connect&quot;);
   goto bad;
  }
#ifdef IP_TOS
  on = IPTOS_THROUGHPUT;
  if (setsockopt(data, IPPROTO_IP, IP_TOS, (char *)&amp;amp;on,
          sizeof(int)) &amp;lt; 0)
   perror(&quot;ftp: setsockopt TOS (ignored)&quot;);
#endif
  return(0);
 }

noport:
 data_addr = myctladdr;
 if (sendport)
  data_addr.sin_port = 0; /* let system pick one */ 
 if (data != -1)
  (void) close(data);
 data = socket(AF_INET, SOCK_STREAM, 0);
 if (data &amp;lt; 0) {
  warn(&quot;socket&quot;);
  if (tmpno)
   sendport = 1;
  return (1);
 }
 if (!sendport)
  if (setsockopt(data, SOL_SOCKET, SO_REUSEADDR, (char *)&amp;amp;on, sizeof (on)) &amp;lt; 0) {
   warn(&quot;setsockopt (reuse address)&quot;);
   goto bad;
  }
 if (bind(data, (struct sockaddr *)&amp;amp;data_addr, sizeof (data_addr)) &amp;lt; 0) {
  warn(&quot;bind&quot;);
  goto bad;
 }
 if (options &amp;amp; SO_DEBUG &amp;amp;&amp;amp;
     setsockopt(data, SOL_SOCKET, SO_DEBUG, (char *)&amp;amp;on, sizeof (on)) &amp;lt; 0)
  warn(&quot;setsockopt (ignored)&quot;);
 len = sizeof (data_addr);
 if (getsockname(data, (struct sockaddr *)&amp;amp;data_addr, &amp;amp;len) &amp;lt; 0) {
  warn(&quot;getsockname&quot;);
  goto bad;
 }
 if (listen(data, 1) &amp;lt; 0)
  warn(&quot;listen&quot;);
 if (sendport) {
  a = (char *)&amp;amp;data_addr.sin_addr;
  p = (char *)&amp;amp;data_addr.sin_port;
#define UC(b) (((int)b)&amp;amp;0xff)
  result =
      command(&quot;PORT %d,%d,%d,%d,%d,%d&quot;,
        UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
        UC(p[0]), UC(p[1]));
  if (result == ERROR &amp;amp;&amp;amp; sendport == -1) {
   sendport = 0;
   tmpno = 1;
   goto noport;
  }
  return (result != COMPLETE);
 }
 if (tmpno)
  sendport = 1;
#ifdef IP_TOS
 on = IPTOS_THROUGHPUT;
 if (setsockopt(data, IPPROTO_IP, IP_TOS, (char *)&amp;amp;on, sizeof(int)) &amp;lt; 0)
  warn(&quot;setsockopt TOS (ignored)&quot;);
#endif
 return (0);
bad:
 (void) close(data), data = -1;
 if (tmpno)
  sendport = 1;
 return (1);
}

FILE *
dataconn(lmode)
 char *lmode;
{
 struct sockaddr_in from;
 int s, fromlen = sizeof (from), tos;

 if (passivemode)
  return (fdopen(data, lmode));

 s = accept(data, (struct sockaddr *) &amp;amp;from, &amp;amp;fromlen);
 if (s &amp;lt; 0) {
  warn(&quot;accept&quot;);
  (void) close(data), data = -1;
  return (NULL);
 }
 (void) close(data);
 data = s;
#ifdef IP_TOS
 tos = IPTOS_THROUGHPUT;
 if (setsockopt(s, IPPROTO_IP, IP_TOS, (char *)&amp;amp;tos, sizeof(int)) &amp;lt; 0)
  warn(&quot;setsockopt TOS (ignored)&quot;);
#endif
 return (fdopen(data, lmode));
}

void
ptransfer(direction, bytes, t0, t1)
 char *direction;
 long bytes;
 struct timeval *t0, *t1;
{
 struct timeval td;
 float s;
 long bs;

 if (verbose) {
  tvsub(&amp;amp;td, t1, t0);
  s = td.tv_sec + (td.tv_usec / 1000000.);
#define nz(x) ((x) == 0 ? 1 : (x))
  bs = bytes / nz(s);
  printf(&quot;%ld bytes %s in %.3g seconds (%ld bytes/s)\n&quot;,
      bytes, direction, s, bs);
 }
}

/*
void
tvadd(tsum, t0)
 struct timeval *tsum, *t0;
{

 tsum-&amp;gt;tv_sec += t0-&amp;gt;tv_sec;
 tsum-&amp;gt;tv_usec += t0-&amp;gt;tv_usec;
 if (tsum-&amp;gt;tv_usec &amp;gt; 1000000)
  tsum-&amp;gt;tv_sec++, tsum-&amp;gt;tv_usec -= 1000000;
}
*/

void
tvsub(tdiff, t1, t0)
 struct timeval *tdiff, *t1, *t0;
{

 tdiff-&amp;gt;tv_sec = t1-&amp;gt;tv_sec - t0-&amp;gt;tv_sec;
 tdiff-&amp;gt;tv_usec = t1-&amp;gt;tv_usec - t0-&amp;gt;tv_usec;
 if (tdiff-&amp;gt;tv_usec &amp;lt; 0)
  tdiff-&amp;gt;tv_sec--, tdiff-&amp;gt;tv_usec += 1000000;
}

void
psabort()
{

 abrtflag++;
}

void
pswitch(flag)
 int flag;
{
 sig_t oldintr;
 static struct comvars {
  int connect;
  char name[MAXHOSTNAMELEN];
  struct sockaddr_in mctl;
  struct sockaddr_in hctl;
  FILE *in;
  FILE *out;
  int tpe;
  int curtpe;
  int cpnd;
  int sunqe;
  int runqe;
  int mcse;
  int ntflg;
  char nti[17];
  char nto[17];
  int mapflg;
  char mi[MAXPATHLEN];
  char mo[MAXPATHLEN];
 } proxstruct, tmpstruct;
 struct comvars *ip, *op;

 abrtflag = 0;
 oldintr = signal(SIGINT, psabort);
 if (flag) {
  if (proxy)
   return;
  ip = &amp;amp;tmpstruct;
  op = &amp;amp;proxstruct;
  proxy++;
 } else {
  if (!proxy)
   return;
  ip = &amp;amp;proxstruct;
  op = &amp;amp;tmpstruct;
  proxy = 0;
 }
 ip-&amp;gt;connect = connected;
 connected = op-&amp;gt;connect;
 if (hostname) {
  (void) strncpy(ip-&amp;gt;name, hostname, sizeof(ip-&amp;gt;name) - 1);
  ip-&amp;gt;name[strlen(ip-&amp;gt;name)] = &#39;\0&#39;;
 } else
  ip-&amp;gt;name[0] = 0;
 hostname = op-&amp;gt;name;
 ip-&amp;gt;hctl = hisctladdr;
 hisctladdr = op-&amp;gt;hctl;
 ip-&amp;gt;mctl = myctladdr;
 myctladdr = op-&amp;gt;mctl;
 ip-&amp;gt;in = cin;
 cin = op-&amp;gt;in;
 ip-&amp;gt;out = cout;
 cout = op-&amp;gt;out;
 ip-&amp;gt;tpe = type;
 type = op-&amp;gt;tpe;
 ip-&amp;gt;curtpe = curtype;
 curtype = op-&amp;gt;curtpe;
 ip-&amp;gt;cpnd = cpend;
 cpend = op-&amp;gt;cpnd;
 ip-&amp;gt;sunqe = sunique;
 sunique = op-&amp;gt;sunqe;
 ip-&amp;gt;runqe = runique;
 runique = op-&amp;gt;runqe;
 ip-&amp;gt;mcse = mcase;
 mcase = op-&amp;gt;mcse;
 ip-&amp;gt;ntflg = ntflag;
 ntflag = op-&amp;gt;ntflg;
 (void) strncpy(ip-&amp;gt;nti, ntin, 16);
 (ip-&amp;gt;nti)[strlen(ip-&amp;gt;nti)] = &#39;\0&#39;;
 (void) strcpy(ntin, op-&amp;gt;nti);
 (void) strncpy(ip-&amp;gt;nto, ntout, 16);
 (ip-&amp;gt;nto)[strlen(ip-&amp;gt;nto)] = &#39;\0&#39;;
 (void) strcpy(ntout, op-&amp;gt;nto);
 ip-&amp;gt;mapflg = mapflag;
 mapflag = op-&amp;gt;mapflg;
 (void) strncpy(ip-&amp;gt;mi, mapin, MAXPATHLEN - 1);
 (ip-&amp;gt;mi)[strlen(ip-&amp;gt;mi)] = &#39;\0&#39;;
 (void) strcpy(mapin, op-&amp;gt;mi);
 (void) strncpy(ip-&amp;gt;mo, mapout, MAXPATHLEN - 1);
 (ip-&amp;gt;mo)[strlen(ip-&amp;gt;mo)] = &#39;\0&#39;;
 (void) strcpy(mapout, op-&amp;gt;mo);
 (void) signal(SIGINT, oldintr);
 if (abrtflag) {
  abrtflag = 0;
  (*oldintr)(SIGINT);
 }
}

void
abortpt()
{

 printf(&quot;\n&quot;);
 (void) fflush(stdout);
 ptabflg++;
 mflag = 0;
 abrtflag = 0;
 longjmp(ptabort, 1);
}

void
proxtrans(cmd, local, remote)
 char *cmd, *local, *remote;
{
 sig_t oldintr;
 int secndflag = 0, prox_type, nfnd;
 char *cmd2;
 struct fd_set mask;

 if (strcmp(cmd, &quot;RETR&quot;))
  cmd2 = &quot;RETR&quot;;
 else
  cmd2 = runique ? &quot;STOU&quot; : &quot;STOR&quot;;
 if ((prox_type = type) == 0) {
  if (unix_server &amp;amp;&amp;amp; unix_proxy)
   prox_type = TYPE_I;
  else
   prox_type = TYPE_A;
 }
 if (curtype != prox_type)
  changetype(prox_type, 1);
 if (command(&quot;PASV&quot;) != COMPLETE) {
  printf(&quot;proxy server does not support third party transfers.\n&quot;);
  return;
 }
 pswitch(0);
 if (!connected) {
  printf(&quot;No primary connection\n&quot;);
  pswitch(1);
  code = -1;
  return;
 }
 if (curtype != prox_type)
  changetype(prox_type, 1);
 if (command(&quot;PORT %s&quot;, pasv) != COMPLETE) {
  pswitch(1);
  return;
 }
 if (setjmp(ptabort))
  goto abort;
 oldintr = signal(SIGINT, abortpt);
 if (command(&quot;%s %s&quot;, cmd, remote) != PRELIM) {
  (void) signal(SIGINT, oldintr);
  pswitch(1);
  return;
 }
 sleep(2);
 pswitch(1);
 secndflag++;
 if (command(&quot;%s %s&quot;, cmd2, local) != PRELIM)
  goto abort;
 ptflag++;
 (void) getreply(0);
 pswitch(0);
 (void) getreply(0);
 (void) signal(SIGINT, oldintr);
 pswitch(1);
 ptflag = 0;
 printf(&quot;local: %s remote: %s\n&quot;, local, remote);
 return;
abort:
 (void) signal(SIGINT, SIG_IGN);
 ptflag = 0;
 if (strcmp(cmd, &quot;RETR&quot;) &amp;amp;&amp;amp; !proxy)
  pswitch(1);
 else if (!strcmp(cmd, &quot;RETR&quot;) &amp;amp;&amp;amp; proxy)
  pswitch(0);
 if (!cpend &amp;amp;&amp;amp; !secndflag) {  /* only here if cmd = &quot;STOR&quot; (proxy=1) */
  if (command(&quot;%s %s&quot;, cmd2, local) != PRELIM) {
   pswitch(0);
   if (cpend)
    abort_remote((FILE *) NULL);
  }
  pswitch(1);
  if (ptabflg)
   code = -1;
  (void) signal(SIGINT, oldintr);
  return;
 }
 if (cpend)
  abort_remote((FILE *) NULL);
 pswitch(!proxy);
 if (!cpend &amp;amp;&amp;amp; !secndflag) {  /* only if cmd = &quot;RETR&quot; (proxy=1) */
  if (command(&quot;%s %s&quot;, cmd2, local) != PRELIM) {
   pswitch(0);
   if (cpend)
    abort_remote((FILE *) NULL);
   pswitch(1);
   if (ptabflg)
    code = -1;
   (void) signal(SIGINT, oldintr);
   return;
  }
 }
 if (cpend)
  abort_remote((FILE *) NULL);
 pswitch(!proxy);
 if (cpend) {
  FD_ZERO(&amp;amp;mask);
  FD_SET(fileno(cin), &amp;amp;mask);
  if ((nfnd = empty(&amp;amp;mask, 10)) &amp;lt;= 0) {
   if (nfnd &amp;lt; 0) {
    warn(&quot;abort&quot;);
   }
   if (ptabflg)
    code = -1;
   lostpeer();
  }
  (void) getreply(0);
  (void) getreply(0);
 }
 if (proxy)
  pswitch(0);
 pswitch(1);
 if (ptabflg)
  code = -1;
 (void) signal(SIGINT, oldintr);
}

void
reset(argc, argv)
 int argc;
 char *argv[];
{
 struct fd_set mask;
 int nfnd = 1;

 FD_ZERO(&amp;amp;mask);
 while (nfnd &amp;gt; 0) {
  FD_SET(fileno(cin), &amp;amp;mask);
  if ((nfnd = empty(&amp;amp;mask,0)) &amp;lt; 0) {
   warn(&quot;reset&quot;);
   code = -1;
   lostpeer();
  }
  else if (nfnd) {
   (void) getreply(0);
  }
 }
}

char *
gunique(local)
 char *local;
{
 static char new[MAXPATHLEN];
 char *cp = strrchr(local, &#39;/&#39;);
 int d, count=0;
 char ext = &#39;1&#39;;

 if (cp)
  *cp = &#39;\0&#39;;
 d = access(cp ? local : &quot;.&quot;, 2);
 if (cp)
  *cp = &#39;/&#39;;
 if (d &amp;lt; 0) {
  warn(&quot;local: %s&quot;, local);
  return ((char *) 0);
 }
 (void) strcpy(new, local);
 cp = new + strlen(new);
 *cp++ = &#39;.&#39;;
 while (!d) {
  if (++count == 100) {
   printf(&quot;runique: can&#39;t find unique file name.\n&quot;);
   return ((char *) 0);
  }
  *cp++ = ext;
  *cp = &#39;\0&#39;;
  if (ext == &#39;9&#39;)
   ext = &#39;0&#39;;
  else
   ext++;
  if ((d = access(new, 0)) &amp;lt; 0)
   break;
  if (ext != &#39;0&#39;)
   cp--;
  else if (*(cp - 2) == &#39;.&#39;)
   *(cp - 1) = &#39;1&#39;;
  else {
   *(cp - 2) = *(cp - 2) + 1;
   cp--;
  }
 }
 return (new);
}

void
abort_remote(din)
 FILE *din;
{
 char buf[BUFSIZ];
 int nfnd;
 struct fd_set mask;

 /*
  * send IAC in urgent mode instead of DM because 4.3BSD places oob mark
  * after urgent byte rather than before as is protocol now
  */
 sprintf(buf, &quot;%c%c%c&quot;, IAC, IP, IAC);
 if (send(fileno(cout), buf, 3, MSG_OOB) != 3)
  warn(&quot;abort&quot;);
 fprintf(cout,&quot;%cABOR\r\n&quot;, DM);
 (void) fflush(cout);
 FD_ZERO(&amp;amp;mask);
 FD_SET(fileno(cin), &amp;amp;mask);
 if (din) { 
  FD_SET(fileno(din), &amp;amp;mask);
 }
 if ((nfnd = empty(&amp;amp;mask, 10)) &amp;lt;= 0) {
  if (nfnd &amp;lt; 0) {
   warn(&quot;abort&quot;);
  }
  if (ptabflg)
   code = -1;
  lostpeer();
 }
 if (din &amp;amp;&amp;amp; FD_ISSET(fileno(din), &amp;amp;mask)) {
  while (read(fileno(din), buf, BUFSIZ) &amp;gt; 0)
   /* LOOP */;
 }
 if (getreply(0) == ERROR &amp;amp;&amp;amp; code == 552) {
  /* 552 needed for nic style abort */
  (void) getreply(0);
 }
 (void) getreply(0);
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;</description><link>http://simplestcodings.blogspot.com/2012/09/ftp-implementation-in-c.html</link><author>noreply@blogger.com (Varun)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgBF0T31WXW0AKpxMaQfg0FkDLnjBpQOCNUpKuIK_4hswYNROrZUDb6zhHsLFssekSVDvfkTaaJeYM5xHk4trVDG9nhE8qCBt4GQbaPyr2c2bcTPW8lZ8mYsKgX1sfpLQYJr40-IhYowJR6nUt9-95ahynhYaPN3RcxD3bEhKgXZZralcurHfUzb1yYmYY/s72-c/ftp.jpeg" height="72" width="72"/><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-3459284654925679524.post-647300920750858334</guid><pubDate>Thu, 28 Jun 2012 18:42:00 +0000</pubDate><atom:updated>2018-05-01T09:07:42.991+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">SSC 2018</category><category domain="http://www.blogger.com/atom/ns#">SSC Adit card 2018</category><category domain="http://www.blogger.com/atom/ns#">SSC Combined Graduate Level Examination 2012 Admit Card</category><category domain="http://www.blogger.com/atom/ns#">SSC Exam 2018</category><title>SSC Combined Graduate Level Examination 2012 Admit Card</title><description>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
This would be helpful to those candidates who are having trouble finding their Admit Card for&amp;nbsp; SSC Combined Graduate Level Examination 2012.&lt;br /&gt;
&lt;br /&gt;
Please visit your local(state) SSC website and download the list of eligible candidates from there.&lt;br /&gt;
You can find your Roll No. Enlisted there and then it could be used to retrieve the Admit Card from the same site.&lt;br /&gt;
&lt;br /&gt;
For Example, In Karntaka roll no. can be found using following steps:&lt;br /&gt;
&lt;br /&gt;
1. Visit &lt;a href=&quot;http://www.ssckkr.kar.nic.in/&quot;&gt;http://www.ssckkr.kar.nic.in/&lt;/a&gt;&lt;br /&gt;
2. On the homepage find the link&lt;br /&gt;
&lt;span class=&quot;style8&quot;&gt;&lt;span class=&quot;style8&quot;&gt;&lt;span class=&quot;style9&quot;&gt;&lt;span class=&quot;style10&quot;&gt;&lt;span class=&quot;style13&quot;&gt;&lt;a class=&quot;style11&quot; href=&quot;http://www.ssckkr.kar.nic.in/PROVISIONALLY_ACCEPTcgl12.pdf&quot;&gt;1.&#39;&quot;Click here to see the Roll NO. of the list of the provisionally eligible candidates for Combined Graduate Level Exam, 2012&quot;.&lt;/a&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
&lt;span class=&quot;style8&quot;&gt;&lt;span class=&quot;style8&quot;&gt;&lt;span class=&quot;style9&quot;&gt;&lt;span class=&quot;style10&quot;&gt;&lt;span class=&quot;style13&quot;&gt;3. Then try to search your name in the list.&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
&lt;span class=&quot;style8&quot;&gt;&lt;span class=&quot;style8&quot;&gt;&lt;span class=&quot;style9&quot;&gt;&lt;span class=&quot;style10&quot;&gt;&lt;span class=&quot;style13&quot;&gt;4. Then visit the link &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;a href=&quot;http://www.ssckkr.kar.nic.in/sschallticket/CGLE2012/result.asp&quot;&gt;1.Download Duplicate Admission Certificates for Combined Graduate Level EXAMINATION 2012 scheduled to be held on 01.07.2012&lt;/a&gt;&lt;br /&gt;
&lt;span class=&quot;style8&quot;&gt;&lt;span class=&quot;style8&quot;&gt;&lt;span class=&quot;style9&quot;&gt;&lt;span class=&quot;style10&quot;&gt;&lt;span class=&quot;style13&quot;&gt;5. Enter your roll no. there and download your admit card.&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;span class=&quot;style8&quot;&gt;&lt;span class=&quot;style8&quot;&gt;&lt;span class=&quot;style9&quot;&gt;&lt;span class=&quot;style10&quot;&gt;&lt;span class=&quot;style13&quot;&gt;This steps is valid for Karnataka State Candidates, It might be valid for other states too but somebody will have to check.&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;span class=&quot;style8&quot;&gt;&lt;span class=&quot;style8&quot;&gt;&lt;span class=&quot;style9&quot;&gt;&lt;span class=&quot;style10&quot;&gt;&lt;span class=&quot;style13&quot;&gt;These are sites for various regions&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
&lt;h3 style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace; text-align: left;&quot;&gt;


&lt;b&gt;&lt;i&gt;&lt;a href=&quot;http://sscnr.net.in/newlook/cgladmintcard2012/additional_cisf_cisf_2012.aspx&quot; target=&quot;_blank&quot;&gt;SSC Northern Region Delhi (SSCNR)&lt;/a&gt;&lt;/i&gt;&lt;/b&gt;&lt;/h3&gt;
&lt;h3 style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace; text-align: left;&quot;&gt;


&lt;b&gt;&lt;i&gt;&lt;a href=&quot;http://www.sscnwr.org/cgl_tier_1_2012.php&quot; target=&quot;_blank&quot;&gt;SSC North Western Region Chandigarh&lt;/a&gt;&lt;/i&gt;&lt;/b&gt;&lt;/h3&gt;
&lt;h3 style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace; text-align: left;&quot;&gt;


&lt;b&gt;&lt;i&gt;&lt;a href=&quot;http://www.ssc-cr.org/cgl_tier_1_2012.php&quot; target=&quot;_blank&quot;&gt;SSC Central Region (SSCCR) Allahabad&lt;/a&gt;&lt;/i&gt;&lt;/b&gt;&lt;/h3&gt;
&lt;h3 style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace; text-align: left;&quot;&gt;


&lt;b&gt;&lt;i&gt;&lt;a href=&quot;http://www.sscer.org/MATTER/DOWNLOAD_AC.html&quot; target=&quot;_blank&quot;&gt;SSC Eastern Region Kolkata (SSCER)&lt;/a&gt;&lt;/i&gt;&lt;/b&gt;&lt;/h3&gt;
&lt;h3 style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace; text-align: left;&quot;&gt;


&lt;b&gt;&lt;i&gt;&lt;a href=&quot;http://www.sscner.org.in/CGL2012/admit.asp&quot; target=&quot;_blank&quot;&gt;SSC North Eastern Region (SSCNER) Guwahati&lt;/a&gt;&lt;/i&gt;&lt;/b&gt;&lt;/h3&gt;
&lt;h3 style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace; text-align: left;&quot;&gt;


&lt;b&gt;&lt;i&gt;&lt;a href=&quot;http://sscmpr.org/index.php?Page=cgl_tier_1_2012&quot; target=&quot;_blank&quot;&gt;SSC Madhya Pradesh Region (SSCMPR)&lt;/a&gt;&lt;/i&gt;&lt;/b&gt;&lt;/h3&gt;
&lt;h3 style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace; text-align: left;&quot;&gt;


&lt;b&gt;&lt;i&gt;SSC Southern Region (SSCSR)&lt;/i&gt;&lt;/b&gt; &lt;b&gt;&lt;a href=&quot;http://www.sscsr.gov.in/CGL-2012-FN.htm&quot; target=&quot;_blank&quot;&gt;(Forenoon)&lt;/a&gt;&lt;/b&gt;&amp;nbsp;|| &lt;a href=&quot;http://www.sscsr.gov.in/CGL-2012-AN.htm&quot; target=&quot;_blank&quot;&gt;&lt;b&gt;(Afternoon)&lt;/b&gt;&lt;/a&gt;&lt;/h3&gt;
&lt;h3 style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace; text-align: left;&quot;&gt;


&lt;b&gt;&lt;i&gt;&lt;a href=&quot;http://sscwr.net/index.php?Page=cgl_tier_1_2012&quot; target=&quot;_blank&quot;&gt;SSC Western Region (SSCWR) Maharashtra&lt;/a&gt;&lt;/i&gt;&lt;/b&gt;&lt;/h3&gt;
&lt;h3 style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace; text-align: left;&quot;&gt;


&lt;b&gt;&lt;i&gt;&lt;a href=&quot;http://www.ssckkr.kar.nic.in/sschallticket/CGLE2012/result.asp&quot; target=&quot;_blank&quot;&gt;SSC Kerala, Karnataka Region (SSCKKR)&lt;/a&gt;&lt;/i&gt;&lt;/b&gt;&lt;/h3&gt;
&lt;h3 style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace; text-align: left;&quot;&gt;


&lt;b&gt;&lt;i&gt;&amp;nbsp;&lt;/i&gt;&lt;/b&gt;&lt;/h3&gt;
&lt;div style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace; text-align: left;&quot;&gt;
&lt;b&gt;&lt;i&gt;&lt;u&gt;&lt;b style=&quot;font-family: inherit;&quot;&gt;&lt;span style=&quot;font-weight: normal;&quot;&gt;&lt;/span&gt;&lt;/b&gt;&lt;span style=&quot;font-family: inherit;&quot;&gt;&lt;span style=&quot;font-weight: normal;&quot;&gt;Whereever you have filled the centre of examination , that will be you region &lt;/span&gt;&lt;/span&gt;&lt;/u&gt;&lt;/i&gt;&lt;/b&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;span class=&quot;style8&quot;&gt;&lt;span class=&quot;style8&quot;&gt;&lt;span class=&quot;style9&quot;&gt;&lt;span class=&quot;style10&quot;&gt;&lt;span class=&quot;style13&quot;&gt;&amp;nbsp;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;style8&quot;&gt;&lt;span class=&quot;style8&quot;&gt;&lt;span class=&quot;style9&quot;&gt;&lt;span class=&quot;style10&quot;&gt;&lt;span class=&quot;style13&quot;&gt; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/div&gt;
</description><link>http://simplestcodings.blogspot.com/2012/06/ssc-combined-graduate-level-examination.html</link><author>noreply@blogger.com (Varun)</author><thr:total>26</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-3459284654925679524.post-5976287721405048255</guid><pubDate>Thu, 23 Feb 2012 13:10:00 +0000</pubDate><atom:updated>2023-12-21T00:41:52.437+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">C++</category><category domain="http://www.blogger.com/atom/ns#">Libconfig</category><category domain="http://www.blogger.com/atom/ns#">Read configuration files</category><title>libconfig to read configuration files in C/C++</title><description>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
There are so many open-source libraries already available for parsing configuration files in c/c++ , but still we there are some which make their place up than rest of the others. One such library is &lt;a href=&quot;http://www.hyperrealm.com/libconfig/&quot; target=&quot;_blank&quot;&gt;libconfig&amp;nbsp;&lt;/a&gt;. The reason being its simplicity and much lesser memory footprint. Most of the library for configuration files are XML based , but this library is text based and the structure of the configuration files is pretty simple.&lt;br /&gt;
e.g. In its simplest form a configuration file can look like :&lt;br /&gt;
&lt;span style=&quot;text-align: -webkit-auto; white-space: pre-wrap;&quot;&gt;&lt;br /&gt;&lt;/span&gt;&lt;br /&gt;
&lt;div style=&quot;text-align: -webkit-auto;&quot;&gt;
&lt;/div&gt;
&lt;pre style=&quot;white-space: pre-wrap; word-wrap: break-word;&quot;&gt;port = 5000;&lt;/pre&gt;
&lt;br /&gt;
&lt;br /&gt;
It can provide even more simpler configuration file for much complex data group. For example :&lt;br /&gt;
&lt;br /&gt;
&lt;pre style=&quot;text-align: -webkit-auto; white-space: pre-wrap; word-wrap: break-word;&quot;&gt;books = ( &quot;inventory&quot;,
          { title  = &quot;Treasure Island&quot;;
            author = &quot;Robert Louis Stevenson&quot;;
            price  = 29.99;
            qty    = 5; },
          { title  = &quot;Snow Crash&quot;;
            author = &quot;Neal Stephenson&quot;;
            price  = 9.99;
            qty    = 8; },&amp;nbsp;&lt;/pre&gt;
&lt;span style=&quot;text-align: -webkit-auto; white-space: pre-wrap;&quot;&gt;          { } );&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
Here there is a set of data for the inventory of books with multiple fields for each book.&lt;br /&gt;
&lt;br /&gt;
One of the most important feature of this library is that it supports a&lt;span style=&quot;text-align: -webkit-auto;&quot;&gt;&amp;nbsp;fully re-entrant parser which means that different configurations can be parsed in concurrent threads at the same time. Moreover the APIs are available for both C and C++ languages and there are hooks provided in the library to facilitate its use in other programming languages too.&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;text-align: -webkit-auto;&quot;&gt;&lt;br /&gt;&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;text-align: -webkit-auto;&quot;&gt;The detailed documentation of this library can be found at&amp;nbsp;&lt;/span&gt;&lt;a href=&quot;http://www.hyperrealm.com/libconfig/libconfig_manual.html&quot;&gt;Libconfig Manual&lt;/a&gt;. It supports multiple platforms such as Windows, Linux , Mac OS X and Solaris (POSIX compliant platforms).&lt;br /&gt;
&lt;br /&gt;
To use it in a C/C++ program one just needs to add a single preprocessor directive&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;smallexample&quot; style=&quot;font-size: smaller; text-align: -webkit-auto;&quot;&gt;&lt;/pre&gt;
&lt;pre class=&quot;smallexample&quot; style=&quot;text-align: -webkit-auto;&quot;&gt;#include &amp;lt;libconfig.h&amp;gt;      /*For C*/  &lt;/pre&gt;
&lt;pre class=&quot;smallexample&quot; style=&quot;text-align: -webkit-auto;&quot;&gt;&lt;pre class=&quot;smallexample&quot;&gt;#include &amp;lt;libconfig.h++&amp;gt;    /*For C++*/&lt;/pre&gt;
&lt;/pre&gt;
&lt;pre class=&quot;smallexample&quot; style=&quot;text-align: -webkit-auto;&quot;&gt;&lt;/pre&gt;
&lt;br /&gt;
&lt;span style=&quot;font-family: Times, &#39;Times New Roman&#39;, serif;&quot;&gt;For dynamic linking -lconfig/-lconfig++ must be used for C/C++ respectively. Otherwise the libraries can be statically linked using the static linking option during the compilation.&amp;nbsp;&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: Times, &#39;Times New Roman&#39;, serif;&quot;&gt;&lt;br /&gt;&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: &#39;Courier New&#39;, Courier, monospace;&quot;&gt;e.g. ( -static $(LIBPTHREAD_INSTALL_DIR)/libpthread.a)&amp;nbsp;&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: Times, &#39;Times New Roman&#39;, serif;&quot;&gt;&lt;br /&gt;&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: Times, &#39;Times New Roman&#39;, serif;&quot;&gt;&lt;b&gt;Issues as per the libconfig &lt;a href=&quot;http://www.hyperrealm.com/libconfig/libconfig_manual.html&quot;&gt;website&lt;/a&gt;:&amp;nbsp;&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: Times, &#39;Times New Roman&#39;, serif;&quot;&gt;&lt;br /&gt;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;div style=&quot;text-align: -webkit-auto;&quot;&gt;
&lt;/div&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;&lt;i&gt;Libconfig&lt;/i&gt;&amp;nbsp;is fully&amp;nbsp;&lt;dfn&gt;reentrant&lt;/dfn&gt;; the functions in the library do not make use of global variables and do not maintain state between successive calls. Therefore two independent configurations may be safely manipulated concurrently by two distinct threads.&lt;/li&gt;
&lt;li&gt;&lt;i&gt;Libconfig&lt;/i&gt;&amp;nbsp;is not&amp;nbsp;&lt;dfn&gt;thread-safe&lt;/dfn&gt;. The library is not aware of the presence of threads and knows nothing about the host system&#39;s threading model. Therefore, if an instance of a configuration is to be accessed from multiple threads, it must be suitably protected by synchronization mechanisms like read-write locks or mutexes; the standard rules for safe multithreaded access to shared data must be observed.&lt;/li&gt;
&lt;li&gt;&lt;i&gt;Libconfig&lt;/i&gt;&amp;nbsp;is not&amp;nbsp;&lt;dfn&gt;async-safe&lt;/dfn&gt;. Calls should not be made into the library from signal handlers, because some of the C library routines that it uses may not be async-safe.&lt;/li&gt;
&lt;li&gt;&lt;i&gt;Libconfig&lt;/i&gt;&amp;nbsp;is not guaranteed to be&amp;nbsp;&lt;dfn&gt;cancel-safe&lt;/dfn&gt;. Since it is not aware of the host system&#39;s threading model, the library does not contain any thread cancellation points. In most cases this will not be an issue for multithreaded programs. However, be aware that some of the routines in the library (namely those that read/write configurations from/to files or streams) perform I/O using C library routines which may potentially block; whether or not these C library routines are cancel-safe depends on the host system.&lt;/li&gt;
&lt;/ul&gt;
&lt;div style=&quot;text-align: left;&quot;&gt;
We will provide a simple example of how to read from a configuration file using libconfig:&lt;/div&gt;
&lt;pre class=&quot;prettyprint&quot;&gt; &lt;code class=&quot;language-cpp&quot;&gt;
/*config.c*/
/*
To compile : gcc -o config config.c -lconfig
To run     : ./config
*/
#include &lt;stdio.h&gt;
#include &lt;libconfig.h&gt;

int main()
{
    config_t cfg;               /*Returns all parameters in this structure */
    config_setting_t *setting;
    const char *str1, *str2;
    int tmp;

    char *config_file_name = &quot;config.txt&quot;;

    /*Initialization */
    config_init(&amp;amp;cfg);

    /* Read the file. If there is an error, report it and exit. */
    if (!config_read_file(&amp;amp;cfg, config_file_name))
    {
        printf(&quot;\n%s:%d - %s&quot;, config_error_file(&amp;amp;cfg), config_error_line(&amp;amp;cfg), config_error_text(&amp;amp;cfg));
        config_destroy(&amp;amp;cfg);
        return -1;
    }

    /* Get the configuration file name. */
    if (config_lookup_string(&amp;amp;cfg, &quot;filename&quot;, &amp;amp;str1))
        printf(&quot;\nFile Type: %s&quot;, str1);
    else
        printf(&quot;\nNo &#39;filename&#39; setting in configuration file.&quot;);

    /*Read the parameter group*/
    setting = config_lookup(&amp;amp;cfg, &quot;params&quot;);
    if (setting != NULL)
    {
        /*Read the string*/
        if (config_setting_lookup_string(setting, &quot;param1&quot;, &amp;amp;str2))
        {
            printf(&quot;\nParam1: %s&quot;, str2);
        }
        else
            printf(&quot;\nNo &#39;param1&#39; setting in configuration file.&quot;);

        /*Read the integer*/
        if (config_setting_lookup_int(setting, &quot;param2&quot;, &amp;amp;tmp))
        {
            printf(&quot;\nParam2: %d&quot;, tmp);
        }
        else
            printf(&quot;\nNo &#39;param2&#39; setting in configuration file.&quot;);

        printf(&quot;\n&quot;);
    }

    config_destroy(&amp;amp;cfg);
}


&lt;/code&gt;&lt;/pre&gt;

And corresponding configuration file : 

&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt; &lt;code class=&quot;language-cpp&quot;&gt;
//config.txt
// Basic Information:
filename = &quot;Sample Configuration File&quot;;

// Parameters
params = 
{
param1 = &quot;Hello&quot;;

param2 = 1234;
};
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
 SyntaxHighlighter.highlight();
&lt;/script&gt;</description><link>http://simplestcodings.blogspot.com/2012/02/libconfig-to-read-configuration-files.html</link><author>noreply@blogger.com (Varun)</author><thr:total>1</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-3459284654925679524.post-3536660542629144989</guid><pubDate>Tue, 14 Feb 2012 06:10:00 +0000</pubDate><atom:updated>2012-02-14T11:40:41.519+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">Generic</category><title>Articles needed !</title><description>Due to lack of time, I am not being able to write more posts. If anyone feels that they have some good topic to write about, please write to me and after moderation i can publish it on the blog.</description><link>http://simplestcodings.blogspot.com/2012/02/articles-needed.html</link><author>noreply@blogger.com (Anonymous)</author><thr:total>1</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-3459284654925679524.post-271216525921643791</guid><pubDate>Sun, 28 Nov 2010 10:35:00 +0000</pubDate><atom:updated>2013-10-01T18:23:46.057+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">Generic</category><title>Serialization using Google protobuf</title><description>Protocol buffers (that&#39;s what protobuf means :)) are a means to serialize structured data. Now you may be wondering what this &#39;serialize&#39; means. &lt;br /&gt;
&lt;br /&gt;
To be brief : Serialization is a process of packing the data structures or objects into sequence of bits so that they can be stored in a file or a buffer and transmitted across the network and then can be retrieved on the same or other system environment. Examples include XML, JSON, ASN.1, YAML, ProtoBuf etc.&lt;br /&gt;
&lt;br /&gt;
Advantages :&lt;br /&gt;
1. Persistent object creation&lt;br /&gt;
2. RPC enabling&lt;br /&gt;
3. Are simple&lt;br /&gt;
4. Save space on disk&lt;br /&gt;
5. Very fast &lt;br /&gt;
6. Platform and language independent&lt;br /&gt;
&lt;br /&gt;
ProtoBuf is available freely from Google (&lt;a 
href=&quot;http://code.google.com/p/protobuf/&quot;&gt;http://code.google.com/p/protobuf/&lt;/a&gt;). Procedure of installation and compilation is present there.&lt;br /&gt;
&lt;br /&gt;
Everything that needs to be serialized is put in a protocol buffer message (a .proto file). This file tells the compiler how the data is to be serialized.&lt;br /&gt;
&lt;br /&gt;
For each field there are setter and getter functions fieldname() is a getter and set_fieldname() is a setter. Remember to use these functions as the exact way it is told here. &lt;br /&gt;
The tutorials for the different languages can be found &lt;a href=&quot;http://code.google.com/apis/protocolbuffers/docs/tutorials.html&quot;&gt;here&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
I present a small simple example to use the protobuf library and there is much more than that one can do with the protobuf :)&lt;br /&gt;
&lt;br /&gt;
To make and run the example (on linux) follow the steps :&lt;br /&gt;
1. Download the tar.gz package from &lt;a href=&quot;http://code.google.com/p/protobuf/downloads/list&quot;&gt;here&lt;/a&gt;&lt;br /&gt;
2. Login as root&lt;br /&gt;
3. Untar it in your home directory (say user1)&lt;br /&gt;
4. Go inside the protobuf directory and run ./configure&lt;br /&gt;
5. Add the path /usr/local/lib to the environment variable LD_LIBRARY_PATH&lt;br /&gt;
6. Then run :&lt;br /&gt;
make&lt;br /&gt;
make install&lt;br /&gt;
7. You are now ready to use the library.&lt;br /&gt;
8. To use protobuf you will need following files (I am explaining for c++ only):&lt;br /&gt;
.cc file&lt;br /&gt;
.proto file&lt;br /&gt;
Makefile&lt;br /&gt;
Rest of the files are generated on the fly.&lt;br /&gt;
&lt;br /&gt;
Here is an example of a Vehicle parts which contains three fields , two mandatory and one optional.&lt;br /&gt;
-Part ID (mandatory)&lt;br /&gt;
-Part Name (mandatory)&lt;br /&gt;
-Vendor (optional)&lt;br /&gt;
&lt;br /&gt;
We write this in .proto file&lt;br /&gt;
&lt;br /&gt;
&lt;!--pre name=&quot;code&quot; class=&quot;cpp&quot;--&gt;
&lt;pre class=brush:cpp&gt;
//partbook.proto
package tutorial;

message Part {
  required string name = 1;
  required int32 partid = 2;        // Unique ID number for this part
  optional string vendor = 3;

}

message PartDetails {
  repeated Part part = 1;
}

&lt;/pre&gt;&lt;br /&gt;
Then we write a c++ program to use the library and .proto to add serialized data to the data file.&lt;br /&gt;
&lt;!--pre name=&quot;code&quot; class=&quot;cpp&quot;--&gt;
&lt;pre class=brush:cpp&gt;/*add_part.cc*/
#include &amp;lt;iostream&amp;gt;
#include &amp;lt;fstream&amp;gt;
#include &amp;lt;string&amp;gt;
#include &quot;partbook.pb.h&quot;
using namespace std;

/* This function fills in a Part message based on user input.*/
void PromptForPart(tutorial::Part* part) {
  cout &amp;lt;&amp;lt; &quot;Enter part ID number: &quot;;
  int partid;
  cin &amp;gt;&amp;gt; partid;
  part-&amp;gt;set_partid(partid);
  cin.ignore(256, &#39;\n&#39;);

  cout &amp;lt;&amp;lt; &quot;Enter part name: &quot;;
  getline(cin, *part-&amp;gt;mutable_name());

  cout &amp;lt;&amp;lt; &quot;Enter vendor name (blank for none): &quot;;
  string vendor;
  getline(cin, vendor);
  if (!vendor.empty()) {
    part-&amp;gt;set_vendor(vendor);
  }

}

/* Main function:  Reads the entire part list from a file,
 * adds one part based on user input, then writes it back out to the same
 *   file.
 */
int main(int argc, char* argv[]) {
  /* Verify that the version of the library that we linked against is
   * compatible with the version of the headers we compiled against.
   */
  GOOGLE_PROTOBUF_VERIFY_VERSION;

  if (argc != 2) {
    cerr &amp;lt;&amp;lt; &quot;Usage:  &quot; &amp;lt;&amp;lt; argv[0] &amp;lt;&amp;lt; &quot; PART_BOOK_FILE&quot; &amp;lt;&amp;lt; endl;
    return -1;
  }

  tutorial::PartDetails part_book;

  {
    // Read the existing part book.
    fstream input(argv[1], ios::in | ios::binary);
    if (!input) {
      cout &amp;lt;&amp;lt; argv[1] &amp;lt;&amp;lt; &quot;: File not found.  Creating a new file.&quot; &amp;lt;&amp;lt; endl;
    } else if (!part_book.ParseFromIstream(&amp;input)) {
      cerr &amp;lt;&amp;lt; &quot;Failed to parse part book.&quot; &amp;lt;&amp;lt; endl;
      return -1;
    }
  }

  // Add a new part.
  PromptForPart(part_book.add_part());

  {
    // Write the new part book back to disk.
    fstream output(argv[1], ios::out | ios::trunc | ios::binary);
    if (!part_book.SerializeToOstream(&amp;output)) {
      cerr &amp;lt;&amp;lt; &quot;Failed to write part book.&quot; &amp;lt;&amp;lt; endl;
      return -1;
    }
  }

  // Optional:  Delete all global objects allocated by libprotobuf.
  google::protobuf::ShutdownProtobufLibrary();

  return 0;
}

&lt;/pre&gt;&lt;br /&gt;
Then we write a c++ program to use the library and .proto to serialize the data.&lt;br /&gt;
&lt;!--pre name=&quot;code&quot; class=&quot;cpp&quot;--&gt;
&lt;pre class=brush:cpp&gt;
/*list_parts.cc*/
#include &amp;lt;iostream&amp;gt;
#include &amp;lt;fstream&amp;gt;
#include &amp;lt;string&amp;gt;
#include &quot;partbook.pb.h&quot;
using namespace std;

// Iterates though all parts in the PartDetails and prints info about them.
void ListParts(const tutorial::PartDetails&amp; part_book) {
  for (int i = 0; i &amp;lt; part_book.part_size(); i++) {
    const tutorial::Part&amp; part = part_book.part(i);

    cout &amp;lt;&amp;lt; &quot;Part ID: &quot; &amp;lt;&amp;lt; part.partid() &amp;lt;&amp;lt; endl;
    cout &amp;lt;&amp;lt; &quot;  Name: &quot; &amp;lt;&amp;lt; part.name() &amp;lt;&amp;lt; endl;
    if (part.has_vendor()) {
      cout &amp;lt;&amp;lt; &quot;  Vendor: &quot; &amp;lt;&amp;lt; part.vendor() &amp;lt;&amp;lt; endl;
    }

  }
}

// Main function:  Reads the entire part book from a file and prints all
//   the information inside.
int main(int argc, char* argv[]) {
  // Verify that the version of the library that we linked against is
  // compatible with the version of the headers we compiled against.
  GOOGLE_PROTOBUF_VERIFY_VERSION;

  if (argc != 2) {
    cerr &amp;lt;&amp;lt; &quot;Usage:  &quot; &amp;lt;&amp;lt; argv[0] &amp;lt;&amp;lt; &quot; PART_BOOK_FILE&quot; &amp;lt;&amp;lt; endl;
    return -1;
  }

  tutorial::PartDetails part_book;

  {
    // Read the existing data file.
    fstream input(argv[1], ios::in | ios::binary);
    if (!part_book.ParseFromIstream(&amp;input)) {
      cerr &amp;lt;&amp;lt; &quot;Failed to parse part book.&quot; &amp;lt;&amp;lt; endl;
      return -1;
    }
  }

  ListParts(part_book);

  // Optional:  Delete all global objects allocated by libprotobuf.
  google::protobuf::ShutdownProtobufLibrary();

  return 0;
}

&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;!--pre name=&quot;code&quot; class=&quot;cpp&quot;--&gt;
&lt;pre class=brush:cpp&gt;
#Makefile
#This creates executables for python cpp and java , to create only one language use #&#39;make cpp&#39; or &#39;make python&#39; or &#39;make java&#39;

.PHONY: all cpp java python clean

all: cpp java python

cpp:    add_part_cpp    list_parts_cpp
java:   add_part_java   list_parts_java
python: add_part_python list_parts_python

clean:
 rm -f add_part_cpp list_parts_cpp add_part_java list_parts_java add_part_python list_parts_python
 rm -f javac_middleman AddPart*.class ListParts*.class com/example/tutorial/*.class
 rm -f protoc_middleman partbook.pb.cc partbook.pb.h partbook.pb2.py com/example/tutorial/PartBookProtos.java
 rm -f *.pyc
 rmdir com/example/tutorial 2&amp;gt;/dev/null || true
 rmdir com/example 2&amp;gt;/dev/null || true
 rmdir com 2&amp;gt;/dev/null || true

protoc_middleman: partbook.proto
 protoc --cpp_out=. --java_out=. --python_out=. partbook.proto
 @touch protoc_middleman

add_part_cpp: add_part.cc protoc_middleman
 pkg-config --cflags protobuf  # fails if protobuf is not installed
 c++ add_part.cc partbook.pb.cc -o add_part_cpp `pkg-config --cflags --libs protobuf`

list_parts_cpp: list_parts.cc protoc_middleman
 pkg-config --cflags protobuf  # fails if protobuf is not installed
 c++ list_parts.cc partbook.pb.cc -o list_parts_cpp `pkg-config --cflags --libs protobuf`

javac_middleman: AddPart.java ListParts.java protoc_middleman
 javac AddPart.java ListParts.java com/example/tutorial/PartBookProtos.java
 @touch javac_middleman

add_part_java: javac_middleman
 @echo &quot;Writing shortcut script add_part_java...&quot;
 @echo &#39;#! /bin/sh&#39; &amp;gt; add_part_java
 @echo &#39;java -classpath .:$$CLASSPATH AddPart &quot;$$@&quot;&#39; &amp;gt;&amp;gt; add_part_java
 @chmod +x add_part_java

list_parts_java: javac_middleman
 @echo &quot;Writing shortcut script list_parts_java...&quot;
 @echo &#39;#! /bin/sh&#39; &amp;gt; list_parts_java
 @echo &#39;java -classpath .:$$CLASSPATH ListParts &quot;$$@&quot;&#39; &amp;gt;&amp;gt; list_parts_java
 @chmod +x list_parts_java

add_part_python: add_part.py protoc_middleman
 @echo &quot;Writing shortcut script add_part_python...&quot;
 @echo &#39;#! /bin/sh&#39; &amp;gt; add_part_python
 @echo &#39;./add_part.py &quot;$$@&quot;&#39; &amp;gt;&amp;gt; add_part_python
 @chmod +x add_part_python

list_parts_python: list_parts.py protoc_middleman
 @echo &quot;Writing shortcut script list_parts_python...&quot;
 @echo &#39;#! /bin/sh&#39; &amp;gt; list_parts_python
 @echo &#39;./list_parts.py &quot;$$@&quot;&#39; &amp;gt;&amp;gt; list_parts_python
 @chmod +x list_parts_python

&lt;/pre&gt;&lt;br /&gt;
Save all these files under &amp;lt;proto-installation-path&amp;gt;/examples/ and run make&lt;br /&gt;
&lt;br /&gt;
To run the example&lt;br /&gt;
./add_part_cpp &amp;lt;data-filename&amp;gt;&lt;br /&gt;
./list_parts_cpp &amp;lt;data-filename&amp;gt;

&lt;script type=&quot;text/javascript&quot;&gt;
 SyntaxHighlighter.highlight();
&lt;/script&gt;</description><link>http://simplestcodings.blogspot.com/2010/11/serialization-using-google-protobuf.html</link><author>noreply@blogger.com (Anonymous)</author><thr:total>2</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-3459284654925679524.post-1043076797488613474</guid><pubDate>Wed, 24 Nov 2010 08:12:00 +0000</pubDate><atom:updated>2013-08-12T16:22:42.175+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">Generic</category><title>Xdotool : Fake Keyboard/Mouse Input Tool</title><description>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
xdotool is a fake keyboard/mouse input tool for linux which is freely available on the internet.&lt;br /&gt;
So whatever you keep typing on the keyboard or kept clicking using the mouse , you can do it now with the help of a script.&lt;br /&gt;
&lt;br /&gt;
One can get the tool downloaded from their website for all versions of linux: &lt;br /&gt;
&lt;a href=&quot;http://www.semicomplete.com/projects/xdotool/&quot;&gt;http://www.semicomplete.com/projects/xdotool&lt;/a&gt;&lt;br /&gt;
There are too many uses you can use xdotool for. For example : If you need to open multiple tabs in a terminal you can use -&lt;br /&gt;
&#39;xdotool key ctrl+shift+t&#39; for as many times as the no. of tabs you need and to close down those tabs use &#39;xdotool ctrl+shift+w&#39;&lt;br /&gt;
&lt;br /&gt;
All this can be written on a script and when the script runs you can see all of that happening without even touching the keyboard or mouse.&lt;br /&gt;
&lt;br /&gt;
The whole documentation is present &lt;a href=&quot;http://www.semicomplete.com/projects/xdotool/xdotool.xhtml&quot;&gt;here&lt;/a&gt; &lt;br /&gt;
&lt;br /&gt;
Here are some examples :&lt;br /&gt;
&lt;br /&gt;
&lt;!--pre class=&quot;cpp&quot; name=&quot;code&quot;--&gt;
&lt;pre class=brush:cpp&gt;
Example: focus the firefox url bar

WID=`xdotool search &quot;Mozilla Firefox&quot; | head -1`
xdotool windowactivate --sync $WID
xdotool key --clearmodifiers ctrl+l


# As of version 2.20100623, you can do this simpler version of above:
xdotool search &quot;Mozilla Firefox&quot; windowactivate --sync key --clearmodifiers ctrl+l
&lt;/pre&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;!--pre class=&quot;cpp&quot; name=&quot;code&quot;--&gt;
&lt;pre class=brush:cpp&gt;
Example: Resize all visible gnome-terminal windows
WIDS=`xdotool search --onlyvisible --name &quot;gnome-terminal&quot;`
for id in $WIDS; do
  xdotool windowsize $id 500 500
done

# As of version 2.20100623, you can do this simpler version of above:
xdotool search --onlyvisible --classname &quot;gnome-terminal&quot; windowsize %@ 500
500

&lt;/pre&gt;

&lt;script src=&#39;http://crux-framework-tools.googlecode.com/svn/trunk/misc/highlight/highlightLoader.js&#39;&gt;&lt;/script&gt;
&lt;/div&gt;</description><link>http://simplestcodings.blogspot.com/2010/11/xdotool-fake-keyboardmouse-input-tool.html</link><author>noreply@blogger.com (Anonymous)</author><thr:total>1</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-3459284654925679524.post-3912277517156357629</guid><pubDate>Sat, 23 Oct 2010 10:09:00 +0000</pubDate><atom:updated>2014-04-29T15:30:27.892+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">Networking</category><title>Create your own packet sniffer in C</title><description>A simple implementation of a packet sniffer in C on linux platform using the libpcap library. This packet sniffer currently sniffs IP , TCP , ICMP and UDP packets. It can be modified to any protocol as needed just by introducing the header information in it.&lt;br /&gt;
&lt;br /&gt;
Certain filters can be used too like port number and specific host etc.&lt;br /&gt;
e.g.&lt;br /&gt;
&lt;br /&gt;
&lt;table border=&quot;0&quot; cellpadding=&quot;0&quot; cellspacing=&quot;0&quot; class=&quot;MsoNormalTable&quot; style=&quot;border-collapse: collapse; margin-left: 4.65pt; width: 483px;&quot;&gt;&lt;tbody&gt;
&lt;tr style=&quot;height: 19.5pt;&quot;&gt;   &lt;td nowrap=&quot;nowrap&quot; style=&quot;-moz-background-clip: border; -moz-background-inline-policy: continuous; -moz-background-origin: padding; background: yellow none repeat scroll 0% 0%; border: 1pt solid windowtext; height: 19.5pt; padding: 0in 5.4pt; width: 114.5pt;&quot; valign=&quot;bottom&quot; width=&quot;153&quot;&gt;&lt;div align=&quot;center&quot; class=&quot;MsoNormal&quot; style=&quot;text-align: center;&quot;&gt;
&lt;b&gt;&lt;span style=&quot;font-family: Arial; font-size: 10pt;&quot;&gt;Expression&lt;/span&gt;&lt;/b&gt;&lt;/div&gt;
&lt;/td&gt;   &lt;td nowrap=&quot;nowrap&quot; style=&quot;-moz-background-clip: border; -moz-background-inline-policy: continuous; -moz-background-origin: padding; background: yellow none repeat scroll 0% 0%; border-color: windowtext windowtext windowtext -moz-use-text-color; border-style: solid solid solid none; border-width: 1pt 1pt 1pt medium; height: 19.5pt; padding: 0in 5.4pt; width: 247.6pt;&quot; valign=&quot;bottom&quot; width=&quot;330&quot;&gt;&lt;div align=&quot;center&quot; class=&quot;MsoNormal&quot; style=&quot;text-align: center;&quot;&gt;
&lt;b&gt;&lt;span style=&quot;font-family: Arial; font-size: 10pt;&quot;&gt;Description&lt;/span&gt;&lt;/b&gt;&lt;/div&gt;
&lt;/td&gt;  &lt;/tr&gt;
&lt;tr style=&quot;height: 19.5pt;&quot;&gt;   &lt;td nowrap=&quot;nowrap&quot; style=&quot;border-color: -moz-use-text-color windowtext windowtext; border-style: none solid solid; border-width: medium 1pt 1pt; height: 19.5pt; padding: 0in 5.4pt; width: 114.5pt;&quot; valign=&quot;bottom&quot; width=&quot;153&quot;&gt;&lt;div class=&quot;MsoNormal&quot;&gt;
&lt;span style=&quot;font-family: Arial; font-size: 10pt;&quot;&gt;&amp;nbsp; ip&lt;/span&gt;&lt;/div&gt;
&lt;/td&gt;   &lt;td nowrap=&quot;nowrap&quot; style=&quot;border-color: -moz-use-text-color windowtext windowtext -moz-use-text-color; border-style: none solid solid none; border-width: medium 1pt 1pt medium; height: 19.5pt; padding: 0in 5.4pt; width: 247.6pt;&quot; valign=&quot;bottom&quot; width=&quot;330&quot;&gt;&lt;div class=&quot;MsoNormal&quot;&gt;
&lt;span style=&quot;font-family: Arial; font-size: 10pt;&quot;&gt;Capture   all IP packets.&lt;/span&gt;&lt;/div&gt;
&lt;/td&gt;  &lt;/tr&gt;
&lt;tr style=&quot;height: 19.5pt;&quot;&gt;   &lt;td nowrap=&quot;nowrap&quot; style=&quot;border-color: -moz-use-text-color windowtext windowtext; border-style: none solid solid; border-width: medium 1pt 1pt; height: 19.5pt; padding: 0in 5.4pt; width: 114.5pt;&quot; valign=&quot;bottom&quot; width=&quot;153&quot;&gt;&lt;div class=&quot;MsoNormal&quot;&gt;
&lt;span style=&quot;font-family: Arial; font-size: 10pt;&quot;&gt;&amp;nbsp; tcp&lt;/span&gt;&lt;/div&gt;
&lt;/td&gt;   &lt;td nowrap=&quot;nowrap&quot; style=&quot;border-color: -moz-use-text-color windowtext windowtext -moz-use-text-color; border-style: none solid solid none; border-width: medium 1pt 1pt medium; height: 19.5pt; padding: 0in 5.4pt; width: 247.6pt;&quot; valign=&quot;bottom&quot; width=&quot;330&quot;&gt;&lt;div class=&quot;MsoNormal&quot;&gt;
&lt;span style=&quot;font-family: Arial; font-size: 10pt;&quot;&gt;Capture   only TCP packets.&lt;/span&gt;&lt;/div&gt;
&lt;/td&gt;  &lt;/tr&gt;
&lt;tr style=&quot;height: 19.5pt;&quot;&gt;   &lt;td nowrap=&quot;nowrap&quot; style=&quot;border-color: -moz-use-text-color windowtext windowtext; border-style: none solid solid; border-width: medium 1pt 1pt; height: 19.5pt; padding: 0in 5.4pt; width: 114.5pt;&quot; valign=&quot;bottom&quot; width=&quot;153&quot;&gt;&lt;div class=&quot;MsoNormal&quot;&gt;
&lt;span style=&quot;font-family: Arial; font-size: 10pt;&quot;&gt;&amp;nbsp; tcp port 80&lt;/span&gt;&lt;/div&gt;
&lt;/td&gt;   &lt;td nowrap=&quot;nowrap&quot; style=&quot;border-color: -moz-use-text-color windowtext windowtext -moz-use-text-color; border-style: none solid solid none; border-width: medium 1pt 1pt medium; height: 19.5pt; padding: 0in 5.4pt; width: 247.6pt;&quot; valign=&quot;bottom&quot; width=&quot;330&quot;&gt;&lt;div class=&quot;MsoNormal&quot;&gt;
&lt;span style=&quot;font-family: Arial; font-size: 10pt;&quot;&gt;Capture   only TCP packets with a port equal to 80.&lt;/span&gt;&lt;/div&gt;
&lt;/td&gt;  &lt;/tr&gt;
&lt;tr style=&quot;height: 19.5pt;&quot;&gt;   &lt;td nowrap=&quot;nowrap&quot; style=&quot;border-color: -moz-use-text-color windowtext windowtext; border-style: none solid solid; border-width: medium 1pt 1pt; height: 19.5pt; padding: 0in 5.4pt; width: 114.5pt;&quot; valign=&quot;bottom&quot; width=&quot;153&quot;&gt;&lt;div class=&quot;MsoNormal&quot;&gt;
&lt;span style=&quot;font-family: Arial; font-size: 10pt;&quot;&gt;&amp;nbsp; ip host 10.1.2.3&lt;/span&gt;&lt;/div&gt;
&lt;/td&gt;   &lt;td nowrap=&quot;nowrap&quot; style=&quot;border-color: -moz-use-text-color windowtext windowtext -moz-use-text-color; border-style: none solid solid none; border-width: medium 1pt 1pt medium; height: 19.5pt; padding: 0in 5.4pt; width: 247.6pt;&quot; valign=&quot;bottom&quot; width=&quot;330&quot;&gt;&lt;div class=&quot;MsoNormal&quot;&gt;
&lt;span style=&quot;font-family: Arial; font-size: 10pt;&quot;&gt;Capture   all IP packets to or from host 10.1.2.3.&lt;/span&gt;&lt;/div&gt;
&lt;/td&gt;  &lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;br /&gt;
It is a little modified version of sniffer from &lt;a href=&quot;http://www.tcpdump.org/&quot;&gt;tcpdump &lt;/a&gt;website.&lt;br /&gt;
&lt;br /&gt;
&lt;div style=&quot;color: red;&quot;&gt;
&lt;b&gt;Note : To run this code you require root permissions.&amp;nbsp;&lt;/b&gt;&lt;/div&gt;
&lt;div style=&quot;color: red;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
Here&#39;s the code: &lt;br /&gt;
&lt;br /&gt;
&lt;!--pre class=&quot;cpp&quot; name=&quot;code&quot;--&gt;
&lt;pre class=brush:cpp&gt;
/*sniffer.c*/
//To compile : gcc -o sniffer sniffer.c -lpcap
//To run : ./sniffer [interface-name]

#include &amp;lt;pcap.h&amp;gt;
#include &amp;lt;stdio.h&amp;gt;
#include &amp;lt;string.h&amp;gt;
#include &amp;lt;stdlib.h&amp;gt;
#include &amp;lt;ctype.h&amp;gt;
#include &amp;lt;errno.h&amp;gt;
#include &amp;lt;sys/types.h&amp;gt;
#include &amp;lt;sys/socket.h&amp;gt;
#include &amp;lt;netinet/in.h&amp;gt;
#include &amp;lt;arpa/inet.h&amp;gt;

/* default snap length (maximum bytes per packet to capture) */
#define SNAP_LEN 1518

/* ethernet headers are always exactly 14 bytes [1] */
#define SIZE_ETHERNET 14

/* Ethernet addresses are 6 bytes */
#define ETHER_ADDR_LEN 6

/* Ethernet header */
struct sniff_ethernet {
        u_char  ether_dhost[ETHER_ADDR_LEN];    /* destination host address */
        u_char  ether_shost[ETHER_ADDR_LEN];    /* source host address */
        u_short ether_type;                     /* IP? ARP? RARP? etc */
};

/* IP header */
struct sniff_ip {
        u_char  ip_vhl;                 /* version &amp;lt;&amp;lt; 4 | header length &amp;gt;&amp;gt; 2 */
        u_char  ip_tos;                 /* type of service */
        u_short ip_len;                 /* total length */
        u_short ip_id;                  /* identification */
        u_short ip_off;                 /* fragment offset field */
        #define IP_RF 0x8000            /* reserved fragment flag */
        #define IP_DF 0x4000            /* dont fragment flag */
        #define IP_MF 0x2000            /* more fragments flag */
        #define IP_OFFMASK 0x1fff       /* mask for fragmenting bits */
        u_char  ip_ttl;                 /* time to live */
        u_char  ip_p;                   /* protocol */
        u_short ip_sum;                 /* checksum */
        struct  in_addr ip_src,ip_dst;  /* source and dest address */
};
#define IP_HL(ip)               (((ip)-&amp;gt;ip_vhl) &amp;amp; 0x0f)
#define IP_V(ip)                (((ip)-&amp;gt;ip_vhl) &amp;gt;&amp;gt; 4)

/* TCP header */
typedef u_int tcp_seq;

struct sniff_tcp {
        u_short th_sport;               /* source port */
        u_short th_dport;               /* destination port */
        tcp_seq th_seq;                 /* sequence number */
        tcp_seq th_ack;                 /* acknowledgement number */
        u_char  th_offx2;               /* data offset, rsvd */
#define TH_OFF(th)      (((th)-&amp;gt;th_offx2 &amp;amp; 0xf0) &amp;gt;&amp;gt; 4)
        u_char  th_flags;
        #define TH_FIN  0x01
        #define TH_SYN  0x02
        #define TH_RST  0x04
        #define TH_PUSH 0x08
        #define TH_ACK  0x10
        #define TH_URG  0x20
        #define TH_ECE  0x40
        #define TH_CWR  0x80
        #define TH_FLAGS        (TH_FIN|TH_SYN|TH_RST|TH_ACK|TH_URG|TH_ECE|TH_CWR)
        u_short th_win;                 /* window */
        u_short th_sum;                 /* checksum */
        u_short th_urp;                 /* urgent pointer */
};

void
got_packet(u_char *args, const struct pcap_pkthdr *header, const u_char *packet);

void
print_payload(const u_char *payload, int len);

void
print_hex_ascii_line(const u_char *payload, int len, int offset);



/*
 * print data in rows of 16 bytes: offset   hex   ascii
 *
 * 00000   47 45 54 20 2f 20 48 54  54 50 2f 31 2e 31 0d 0a   GET / HTTP/1.1..
 */
void
print_hex_ascii_line(const u_char *payload, int len, int offset)
{

 int i;
 int gap;
 const u_char *ch;

 /* offset */
 printf(&quot;%05d   &quot;, offset);
 
 /* hex */
 ch = payload;
 for(i = 0; i &amp;lt; len; i++) {
  printf(&quot;%02x &quot;, *ch);
  ch++;
  /* print extra space after 8th byte for visual aid */
  if (i == 7)
   printf(&quot; &quot;);
 }
 /* print space to handle line less than 8 bytes */
 if (len &amp;lt; 8)
  printf(&quot; &quot;);
 
 /* fill hex gap with spaces if not full line */
 if (len &amp;lt; 16) {
  gap = 16 - len;
  for (i = 0; i &amp;lt; gap; i++) {
   printf(&quot;   &quot;);
  }
 }
 printf(&quot;   &quot;);
 
 /* ascii (if printable) */
 ch = payload;
 for(i = 0; i &amp;lt; len; i++) {
  if (isprint(*ch))
   printf(&quot;%c&quot;, *ch);
  else
   printf(&quot;.&quot;);
  ch++;
 }

 printf(&quot;\n&quot;);

return;
}

/*
 * print packet payload data (avoid printing binary data)
 */
void
print_payload(const u_char *payload, int len)
{

 int len_rem = len;
 int line_width = 16;   /* number of bytes per line */
 int line_len;
 int offset = 0;     /* zero-based offset counter */
 const u_char *ch = payload;

 if (len &amp;lt;= 0)
  return;

 /* data fits on one line */
 if (len &amp;lt;= line_width) {
  print_hex_ascii_line(ch, len, offset);
  return;
 }

 /* data spans multiple lines */
 for ( ;; ) {
  /* compute current line length */
  line_len = line_width % len_rem;
  /* print line */
  print_hex_ascii_line(ch, line_len, offset);
  /* compute total remaining */
  len_rem = len_rem - line_len;
  /* shift pointer to remaining bytes to print */
  ch = ch + line_len;
  /* add offset */
  offset = offset + line_width;
  /* check if we have line width chars or less */
  if (len_rem &amp;lt;= line_width) {
   /* print last line and get out */
   print_hex_ascii_line(ch, len_rem, offset);
   break;
  }
 }

return;
}

/*
 * dissect/print packet
 */
void
got_packet(u_char *args, const struct pcap_pkthdr *header, const u_char *packet)
{

 static int count = 1;                   /* packet counter */
 
 /* declare pointers to packet headers */
 const struct sniff_ethernet *ethernet;  /* The ethernet header [1] */
 const struct sniff_ip *ip;              /* The IP header */
 const struct sniff_tcp *tcp;            /* The TCP header */
 const char *payload;                    /* Packet payload */

 int size_ip;
 int size_tcp;
 int size_payload;
 
 printf(&quot;\nPacket number %d:\n&quot;, count);
 count++;
 
 /* define ethernet header */
 ethernet = (struct sniff_ethernet*)(packet);
 
 /* define/compute ip header offset */
 ip = (struct sniff_ip*)(packet + SIZE_ETHERNET);
 size_ip = IP_HL(ip)*4;
 if (size_ip &amp;lt; 20) {
  printf(&quot;   * Invalid IP header length: %u bytes\n&quot;, size_ip);
  return;
 }

 /* print source and destination IP addresses */
 printf(&quot;       From: %s\n&quot;, inet_ntoa(ip-&amp;gt;ip_src));
 printf(&quot;         To: %s\n&quot;, inet_ntoa(ip-&amp;gt;ip_dst));
 
 /* determine protocol */ 
 switch(ip-&amp;gt;ip_p) {
  case IPPROTO_TCP:
   printf(&quot;   Protocol: TCP\n&quot;);
   break;
  case IPPROTO_UDP:
   printf(&quot;   Protocol: UDP\n&quot;);
   return;
  case IPPROTO_ICMP:
   printf(&quot;   Protocol: ICMP\n&quot;);
   return;
  case IPPROTO_IP:
   printf(&quot;   Protocol: IP\n&quot;);
   return;
  default:
   printf(&quot;   Protocol: unknown\n&quot;);
   return;
 }
 
 /*
  *  OK, this packet is TCP.
  */
 
 /* define/compute tcp header offset */
 tcp = (struct sniff_tcp*)(packet + SIZE_ETHERNET + size_ip);
 size_tcp = TH_OFF(tcp)*4;
 if (size_tcp &amp;lt; 20) {
  printf(&quot;   * Invalid TCP header length: %u bytes\n&quot;, size_tcp);
  return;
 }
 
 printf(&quot;   Src port: %d\n&quot;, ntohs(tcp-&amp;gt;th_sport));
 printf(&quot;   Dst port: %d\n&quot;, ntohs(tcp-&amp;gt;th_dport));
 
 /* define/compute tcp payload (segment) offset */
 payload = (u_char *)(packet + SIZE_ETHERNET + size_ip + size_tcp);
 
 /* compute tcp payload (segment) size */
 size_payload = ntohs(ip-&amp;gt;ip_len) - (size_ip + size_tcp);
 
 /*
  * Print payload data; it might be binary, so don&#39;t just
  * treat it as a string.
  */
 if (size_payload &amp;gt; 0) {
  printf(&quot;   Payload (%d bytes):\n&quot;, size_payload);
  print_payload(payload, size_payload);
 }

return;
}

int main(int argc, char **argv)
{

 char *dev = NULL;   /* capture device name */
 char errbuf[PCAP_ERRBUF_SIZE];  /* error buffer */
 pcap_t *handle;    /* packet capture handle */

 char filter_exp[] = &quot;ip&quot;;  /* filter expression */
 struct bpf_program fp;   /* compiled filter program (expression) */
 bpf_u_int32 mask;   /* subnet mask */
 bpf_u_int32 net;   /* ip */
 int num_packets ;   /* number of packets to capture */

 /* check for capture device name on command-line */
 if (argc == 2) {
  dev = argv[1];
 }
 else if (argc &amp;gt; 3) {
  fprintf(stderr, &quot;error: unrecognized command-line options\n\n&quot;);
 printf(&quot;Usage: %s [interface]\n&quot;, argv[0]);
 printf(&quot;\n&quot;);
 printf(&quot;Options:\n&quot;);
 printf(&quot;    interface    Listen on &amp;lt;interface&amp;gt; for packets.\n&quot;);
 printf(&quot;\n&quot;);
  exit(EXIT_FAILURE);
 }
 else {
  /* find a capture device if not specified on command-line */
  dev = pcap_lookupdev(errbuf);
  if (dev == NULL) {
   fprintf(stderr, &quot;Couldn&#39;t find default device: %s\n&quot;,
       errbuf);
   exit(EXIT_FAILURE);
  }
 }
 printf(&quot;\nEnter no. of packets you want to capture: &quot;);
        scanf(&quot;%d&quot;,&amp;amp;num_packets);
        printf(&quot;\nWhich kind of packets you want to capture : &quot;);
        scanf(&quot;%s&quot;,filter_exp);
 /* get network number and mask associated with capture device */
 if (pcap_lookupnet(dev, &amp;amp;net, &amp;amp;mask, errbuf) == -1) {
  fprintf(stderr, &quot;Couldn&#39;t get netmask for device %s: %s\n&quot;,
      dev, errbuf);
  net = 0;
  mask = 0;
 }

 /* print capture info */
 printf(&quot;Device: %s\n&quot;, dev);
 printf(&quot;Number of packets: %d\n&quot;, num_packets);
 printf(&quot;Filter expression: %s\n&quot;, filter_exp);

 /* open capture device */
 handle = pcap_open_live(dev, SNAP_LEN, 1, 1000, errbuf);
 if (handle == NULL) {
  fprintf(stderr, &quot;Couldn&#39;t open device %s: %s\n&quot;, dev, errbuf);
  exit(EXIT_FAILURE);
 }

 /* make sure we&#39;re capturing on an Ethernet device [2] */
 if (pcap_datalink(handle) != DLT_EN10MB) {
  fprintf(stderr, &quot;%s is not an Ethernet\n&quot;, dev);
  exit(EXIT_FAILURE);
 }

 /* compile the filter expression */
 if (pcap_compile(handle, &amp;amp;fp, filter_exp, 0, net) == -1) {
  fprintf(stderr, &quot;Couldn&#39;t parse filter %s: %s\n&quot;,
      filter_exp, pcap_geterr(handle));
  exit(EXIT_FAILURE);
 }

 /* apply the compiled filter */
 if (pcap_setfilter(handle, &amp;amp;fp) == -1) {
  fprintf(stderr, &quot;Couldn&#39;t install filter %s: %s\n&quot;,
      filter_exp, pcap_geterr(handle));
  exit(EXIT_FAILURE);
 }

 /* now we can set our callback function */
 pcap_loop(handle, num_packets, got_packet, NULL);

 /* cleanup */
 pcap_freecode(&amp;amp;fp);
 pcap_close(handle);

 printf(&quot;\nCapture complete.\n&quot;);

return 0;
}


&lt;/pre&gt;

&lt;script type=&quot;text/javascript&quot;&gt;
 SyntaxHighlighter.highlight();
&lt;/script&gt;</description><link>http://simplestcodings.blogspot.com/2010/10/create-your-own-packet-sniffer-in-c.html</link><author>noreply@blogger.com (Anonymous)</author><thr:total>33</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-3459284654925679524.post-2734109566160910711</guid><pubDate>Tue, 19 Oct 2010 06:47:00 +0000</pubDate><atom:updated>2014-04-29T16:07:46.851+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">System Programming</category><title>Vector Write in C</title><description>Simple implementation of vector writes in unix. This example uses writev system call to write into a file. The writev call enables you to write multiple discontiguous regions of memory to a file descriptor in a single operation.This is called a vector write.&lt;br /&gt;
&lt;br /&gt;
We use iovec structure for the purpose of filling up the vector.Each&lt;br /&gt;
element specifies one region of memory to write; the fields iov_base and iov_len&lt;br /&gt;
specify the address of the start of the region and the length of the region, respectively.&lt;br /&gt;
&lt;br /&gt;
This program takes command line arguments to fill up the vector.&lt;br /&gt;
Anything after the second argument will go to the file.&lt;br /&gt;
&lt;br /&gt;
&lt;!--pre name=&quot;code&quot; class=&quot;cpp&quot;--&gt;
&lt;pre class=brush:cpp&gt;
//vector-write.c
//To compile : gcc -o vwrite vector-write.c
//To run : ./vwrite file-name argument1 argument2 ..

#include &amp;lt;fcntl.h&amp;gt;
#include &amp;lt;stdlib.h&amp;gt;
#include &amp;lt;sys/stat.h&amp;gt;
#include &amp;lt;sys/types.h&amp;gt;
#include &amp;lt;sys/uio.h&amp;gt;
#include &amp;lt;unistd.h&amp;gt;
int main (int argc, char* argv[])
{
  int fd;
  struct iovec* vec;
  struct iovec* vec_next;
  int i;
  
  if(argc &amp;lt; 2 )
  {
    printf(&quot;\nUsage : %s &amp;lt;filename&amp;gt; [args...]\n&quot;,argv[0]);
    exit(1);
  }
  
  char newline = &#39;\n&#39;;
  
  char* filename = argv[1];
  
  argc -= 2;
  argv += 2;
  
  /* Allocate an array of iovec elements. We.ll need two for each
   * element of the argument list, one for the text itself, and one for
   * a newline. */
  
  vec = (struct iovec*) malloc (2 * argc * sizeof (struct iovec));
  
  /* Fill the iovec entries. */
  
  vec_next = vec;
  for (i = 0; i &amp;lt; argc; ++i) {
    
    /* The first element is the text of the argument itself. */
    
    vec_next-&amp;gt;iov_base = argv[i];
    vec_next-&amp;gt;iov_len = strlen (argv[i]);
    ++vec_next;
    
    /* The second element is a single newline character. It.s okay for
     * multiple elements of the struct iovec array to point to the
     * same region of memory. */
    
    vec_next-&amp;gt;iov_base = &amp;newline;
    vec_next-&amp;gt;iov_len = 1;
    ++vec_next;
  }
  
  /* Write the to a file. */
  
  fd = open (filename, O_WRONLY | O_CREAT);
  writev (fd, vec, 2 * argc);
  close (fd);
  free (vec);
  return 0;
}

&lt;/pre&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
 SyntaxHighlighter.highlight();
&lt;/script&gt;</description><link>http://simplestcodings.blogspot.com/2010/10/vector-write-in-c.html</link><author>noreply@blogger.com (Anonymous)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-3459284654925679524.post-4778509727315892229</guid><pubDate>Wed, 13 Oct 2010 05:13:00 +0000</pubDate><atom:updated>2014-04-29T16:10:01.235+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">System Programming</category><title>IPC Memory Map implementation in C</title><description>Using memory mapped file two processes can both open the same file and both read and write from it, thus sharing the information.It is easier to map a section of the file to memory, and get a pointer to it rather than doing fseek .&lt;br /&gt;
&lt;br /&gt;
A memory mapped file is very easy to use as we can perform simple arithmetic operations to get and set data from a file.&lt;br /&gt;
&lt;br /&gt;
Here is a simple example of creating and using memory mapped files.It takes a file and offset as input and tells what data is present at that offset.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;!--pre class=&quot;cpp&quot; name=&quot;code&quot;--&gt;
&lt;pre class=brush:cpp&gt;//memorymap.c
//To compile : gcc -o mmap memorymap.c
//To run : ./mmap file-name offset

#include &amp;lt;stdio.h&amp;gt;
#include &amp;lt;stdlib.h&amp;gt;
#include &amp;lt;fcntl.h&amp;gt;
#include &amp;lt;unistd.h&amp;gt;
#include &amp;lt;sys/types.h&amp;gt;
#include &amp;lt;sys/mman.h&amp;gt;

#include &amp;lt;sys/stat.h&amp;gt;
#include &amp;lt;errno.h&amp;gt;
int main(int argc, char *argv[])
{
    int fd, offset;
    char *data;
    struct stat sbuf;
    if (argc != 3)
    {
        fprintf(stderr, &quot;usage: %s &amp;lt;file-name&amp;gt; offset\n&quot;,argv[0]);
        exit(1);
    }
    if ((fd = open(argv[1], O_RDONLY)) == -1)
    {
        perror(&quot;open&quot;);
        exit(1);
    }
    /*argv[1] is the file name to be examined*/
    if (stat(argv[1], &amp;amp;sbuf) == -1)
    {
        perror(&quot;stat&quot;);
        exit(1);
    }
    offset = atoi(argv[2]);
    if (offset &amp;lt; 0 || offset &amp;gt; sbuf.st_size-1)
    {
        printf(&quot;%s: offset must be in the range 0-%d\n&quot;,argv[0],sbuf.st_size-1);
        exit(1);
    }
    data = mmap((caddr_t)0, sbuf.st_size, PROT_READ, MAP_SHARED, fd, 0);
    {
        if (data == (caddr_t)(-1))
        {
            perror(&quot;mmap&quot;);
            exit(1);
        }
        printf(&quot;Byte at offset %d is &#39;%c&#39;\n&quot;, offset, data[offset]);
        return 0;
    }
}

&lt;/pre&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
 SyntaxHighlighter.highlight();
&lt;/script&gt;</description><link>http://simplestcodings.blogspot.com/2010/10/ipc-memory-map-implementation-in-c.html</link><author>noreply@blogger.com (Anonymous)</author><thr:total>1</thr:total></item></channel></rss>