<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Gordon Passy</title>
    <description>The latest articles on DEV Community by Gordon Passy (@gordonpassy).</description>
    <link>https://dev.to/gordonpassy</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F81005%2F2953904f-5947-467f-9ce2-e24fed6663df.png</url>
      <title>DEV Community: Gordon Passy</title>
      <link>https://dev.to/gordonpassy</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/gordonpassy"/>
    <language>en</language>
    <item>
      <title>Kotlin: Find leaf nodes paths in N-ary tree</title>
      <dc:creator>Gordon Passy</dc:creator>
      <pubDate>Tue, 26 Oct 2021 19:58:04 +0000</pubDate>
      <link>https://dev.to/gordonpassy/kotlin-find-leaf-nodes-paths-in-n-ary-tree-cfc</link>
      <guid>https://dev.to/gordonpassy/kotlin-find-leaf-nodes-paths-in-n-ary-tree-cfc</guid>
      <description>&lt;h2&gt;
  
  
  Definitions
&lt;/h2&gt;

&lt;p&gt;A tree is a data structure where a node can have zero or more children. Each node contains a value and the top-most node is called the &lt;strong&gt;root&lt;/strong&gt;. A node without children is called a &lt;strong&gt;leaf node&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;The &lt;a href="https://www.cct.lsu.edu/~sidhanti/tutorials/data_structures/page255.html"&gt;N-ary tree&lt;/a&gt; is a tree that allows you to have n(n ≥ 0)number of children of a particular node as opposed to binary trees that that allow you to have at most 2 children of a particular node.&lt;/p&gt;

&lt;p&gt;Here's a sample N-ary tree we'll use to get paths to leaf nodes.&lt;br&gt;
&lt;a href="https://postimg.cc/LJN7Ymzr"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--AOclQ-eB--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://i.postimg.cc/nLJtWzMc/n-ary-tree.png" alt="n-ary-tree.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In the above tree, &lt;strong&gt;1&lt;/strong&gt; is the root node, &lt;strong&gt;2&lt;/strong&gt;, &lt;strong&gt;3&lt;/strong&gt; and &lt;strong&gt;4&lt;/strong&gt; are children of the root node. Nodes &lt;strong&gt;5,6,7,8,9,10,11&lt;/strong&gt; are all leaf nodes because they have no children.&lt;/p&gt;
&lt;h2&gt;
  
  
  Task
&lt;/h2&gt;

&lt;p&gt;Given the above N-ary tree, write a solution to get paths to the leaf nodes. The solution should return list of paths to the leaf nodes as shown below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    [1,2,5]
    [1,2,6]
    [1,2,7]
    [1,3,8]
    [1,4,9]
    [1,4,10]
    [1,4,11]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h2&gt;
  
  
  Solution
&lt;/h2&gt;

&lt;p&gt;First, we define the N-ary tree data class.&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;data class Node&amp;lt;T&amp;gt;(var value: T) {
    var parent: Node&amp;lt;T&amp;gt;? = null
    var children: MutableList&amp;lt;Node&amp;lt;T&amp;gt;&amp;gt; = mutableListOf()

     fun addChild(node: Node&amp;lt;T&amp;gt;) {
         children.add(node)
         node.parent = this
     }
    fun hasChildren(): Boolean =
        children.size &amp;gt;= 1
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Next we create a function &lt;code&gt;makeTree()&lt;/code&gt; that constructs the above n-ary tree.&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fun makeTree(): Node&amp;lt;Int&amp;gt; {
    val root =  Node(1)
    val node2 = Node(2)
    root.addChild(node2)
    val node3 = Node(3)
    root.addChild(node3)
    val node4 = Node(4)
    root.addChild(node4)
    val node5 = Node(5)
    node2.addChild(node5)
    val node6 = Node(6)
    node2.addChild(node6)
    val node7 = Node(7)
    node2.addChild(node7)
    val node8 = Node(8);
    node3.addChild(node8)
    val node9 = Node(9)
    node4.addChild(node9)
    val node10 = Node(10)
    node4.addChild(node10)
    val node11 = Node(11)
    node4.addChild(node11)
    return root
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;To get the paths to the leaf nodes we will use Depth First Search. &lt;a href="https://iq.opengenus.org/depth-first-search/"&gt;Depth-first search&lt;/a&gt; (DFS) is an algorithm for traversing or searching tree or graph data structures. One starts at the root (selecting some arbitrary node as the root in the case of a graph) and explores as far as possible along each branch before backtracking.&lt;/p&gt;

&lt;p&gt;We will traverse the N-ary tree and keep inserting every node to the &lt;strong&gt;path&lt;/strong&gt; until a leaf node is found. When a leaf node is found, we add the &lt;strong&gt;path&lt;/strong&gt; to the &lt;strong&gt;result&lt;/strong&gt; and remove the last added leaf node from the &lt;strong&gt;path&lt;/strong&gt; and check for the next leaf node.&lt;/p&gt;

&lt;p&gt;Here's the recursive backtracking routine:&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;private fun findLeafNodePaths(
    node: Node&amp;lt;Int&amp;gt;,
    result: MutableList&amp;lt;List&amp;lt;Int&amp;gt;&amp;gt;,
    path: MutableList&amp;lt;Int&amp;gt;): MutableList&amp;lt;List&amp;lt;Int&amp;gt;&amp;gt; {

    path.add(node.value)
    if (!node.hasChildren()) { // leaf node
        result.add(path.map { it }) // add path to the result
        path.removeLast()//
    } else {
        for (child in node.children) {
            findLeafNodePaths(child, result, path)
        }
        path.removeLast()
    }
    return result
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Here's the main function to create the n-ary tree and print paths to the leaf nodes:&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fun main() {
    findLeafNodePaths(makeTree(),  mutableListOf(), mutableListOf() ).forEach {
        println(it)
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Complete Code: &lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;



</description>
      <category>kotlin</category>
      <category>recursion</category>
      <category>backtracking</category>
      <category>depthfirstsearch</category>
    </item>
    <item>
      <title>Kotlin data class to xml</title>
      <dc:creator>Gordon Passy</dc:creator>
      <pubDate>Wed, 08 Jul 2020 08:47:17 +0000</pubDate>
      <link>https://dev.to/gordonpassy/kotlin-data-class-to-xml-1354</link>
      <guid>https://dev.to/gordonpassy/kotlin-data-class-to-xml-1354</guid>
      <description>&lt;p&gt;Let’s say you have this sample data class that you want to serialize to xml&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;data class SampleDataClass(
        val externalTxnId: String,
        val merchantTxnId: String,
        val reference: String
)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;h3&gt;
  
  
  Steps
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;If you’re using maven, add the &lt;a href="https://github.com/FasterXML/jackson-dataformat-xml"&gt;jackson-dataformat-xml&lt;/a&gt; dependency on your pom.xml file
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;dependency&amp;gt;
   &amp;lt;groupId&amp;gt;com.fasterxml.jackson.dataformat&amp;lt;/groupId&amp;gt;
   &amp;lt;artifactId&amp;gt;jackson-dataformat-xml&amp;lt;/artifactId&amp;gt;
   &amp;lt;version&amp;gt;2.10.1&amp;lt;/version&amp;gt;
&amp;lt;/dependency&amp;gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Initialize the XmlMapper
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;val xmlMapper = XmlMapper(
        JacksonXmlModule().apply { setDefaultUseWrapper(false) }
).apply {
        enable(SerializationFeature.INDENT_OUTPUT)
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Initialize your data class and use the mapper’s writeValueAsString() method to get the xml value.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fun main() {
        val xmlMapper = XmlMapper(
                JacksonXmlModule().apply { setDefaultUseWrapper(false) }
        ).apply {
                enable(SerializationFeature.INDENT_OUTPUT)
                enable(SerializationFeature.WRAP_ROOT_VALUE)
        }

        val data = SampleDataClass(
                externalTxnId = "07026984141550752666",
                merchantTxnId = "07026984141550752666",
                reference     = "MERCHPAY"
        )
        val xml = xmlMapper.writeValueAsString(data)
        println(xml)
}

//This will give out the following output

&amp;lt;SampleDataClass&amp;gt;
  &amp;lt;externalTxnId&amp;gt;07026984141550752666&amp;lt;/externalTxnId&amp;gt;
  &amp;lt;merchantTxnId&amp;gt;07026984141550752666&amp;lt;/merchantTxnId&amp;gt;
  &amp;lt;reference&amp;gt;MERCHPAY&amp;lt;/reference&amp;gt;
&amp;lt;/SampleDataClass&amp;gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Default root element used is the simple name of the data class. So if you don’t want to use the defaults, that’s where the annotation @JacksonXmlRootElement for root element and @JacksonXmlProperty for fields come in.&lt;/p&gt;

&lt;p&gt;Let’s say we want the root element to be labelled COMMAND and the fields externalTxnId to EXTTRID, merchantTxnId to MERCHANT_TXN_ID and finally reference to REFERENCE. To have this implemented we’ll add the annotations to the data class as below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@JacksonXmlRootElement(localName = "COMMAND")
data class SampleDataClass(
        @field:JacksonXmlProperty(localName = "EXTTRID")
        val externalTxnId: String,
        @field:JacksonXmlProperty(localName = "MERCHANT_TXN_ID")
        val merchantTxnId: String,
        @field:JacksonXmlProperty(localName = "REFERENCE")
        val reference: String
)fun main() {
        val xmlMapper = XmlMapper(
                JacksonXmlModule().apply { setDefaultUseWrapper(false) }
        ).apply {
                enable(SerializationFeature.INDENT_OUTPUT)
                enable(SerializationFeature.WRAP_ROOT_VALUE)
        }

        val data = SampleDataClass(
                externalTxnId = "07026984141550752666",
                merchantTxnId = "07026984141550752666",
                reference     = "MERCHPAY"
        )
        val xml = xmlMapper.writeValueAsString(data)
        println(xml)
}//This will give the following output&amp;lt;COMMAND&amp;gt;
  &amp;lt;EXTTRID&amp;gt;07026984141550752666&amp;lt;/EXTTRID&amp;gt;
  &amp;lt;MERCHANT_TXN_ID&amp;gt;07026984141550752666&amp;lt;/MERCHANT_TXN_ID&amp;gt;
  &amp;lt;REFERENCE&amp;gt;MERCHPAY&amp;lt;/REFERENCE&amp;gt;
&amp;lt;/COMMAND&amp;gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



</description>
      <category>kotlin</category>
      <category>springboot</category>
      <category>fasterxml</category>
      <category>xml</category>
    </item>
  </channel>
</rss>
