Thursday, October 19, 2017

Binary tree creation and sorting with inorder traversal using python

class node:

    def __init__(self,data):
        self.left = None
        self.right = None
        self.data = data



    def insert(self,data):
        if(data<self.data):
            if self.left is None:
                self.left = node(data)
            else:
                self.left.insert(data)

        elif(data>self.data):
            if self.right is None:
                self.right = node(data)
            else:
                self.right.insert(data)

        else:
            self.data =data


def check_inorder(root):
    if(root is not None ):
        check_inorder(root.left)
        print (root.data)
        check_inorder(root.right)


def main():


    root = node(8)
    root.insert(5)
    root.insert(10)
    root.insert(1)


    check_inorder(root)




main()

Wednesday, October 18, 2017

binary tree creation and inorder traversal for sorting implemented in c++

//// Created by Laxmi Kadariya on 10/17/17.//
#include "iostream"using namespace std;

struct node{
    int key;
    struct node *left,*right;

};

struct node *newNode(int item)
{
    struct node *temp = new node;
    temp->key = item;
    temp->left = NULL;
    temp->right = NULL;
    return temp;


}

struct node*  insert(node *node,int key)
{
    if (node == NULL)
    {
        return newNode(key);
    }
    if(key<node->key)
    {
        node->left = insert(node->left,key);
    }

    else if(key>node->key)
    {
        node->right = insert(node->right,key);
    }

    return node;

}



struct node* create_binary_tree(int arr[],int n)
{
    struct node *root = NULL;
    root = insert(root,arr[0]);
    for(int i=1;i<n;i++)
    {
        insert(root,arr[i]);
    }

    return root;

}

void storeSorted(node *root, int arr[], int &i)
{
    if (root != NULL)
    {
        storeSorted(root->left, arr, i);
        arr[i++] = root->key;
        storeSorted(root->right, arr, i);
    }
}




int main()
{
    int arr[] = {5,4,7,2,11};
    int n = sizeof(arr)/ sizeof(arr[0]);
    int i =0;
    struct node *root = create_binary_tree(arr,n);

    storeSorted(root,arr,i);

    for (int i=0; i<n; i++)
        cout << arr[i] << " ";







}

Monday, July 17, 2017

Implementation of singly List insertion, deletion with Class in c++

This article explains the concept of singly link list data structure and provides the simple implementation
in C++.



//// Created by Laxmi Kadariya on 7/15/17.//
#include <iostream>using namespace std;


class node{
private:
    int value;
    node* next;

public:
    node(){

    }

    void set_value(int value_arg){
        value = value_arg;
    }

    void set_next(node* next_arg)
    {
        next = next_arg;
    }

    int show_value(){
        return value;

    }

    node* show_next()
    {
        return next;
    }






};

class linklist{
private:
    node* head;

public:
    linklist(){
        head = NULL;
    }
    void add_node(int value);
    void display_node();
    int length_list();
    void del( int value);


};

void linklist::add_node(int value) {
    node *Node = new node();
    Node->set_value(value);
    Node->set_next(NULL);

    node* tmp = head;

    if(tmp == NULL)
    {
        head = Node;


    }
    else    {
        while(tmp->show_next() != NULL)
        {
            tmp = tmp->show_next();
        }
        tmp->set_next(Node);
    }

  cout<<"node"<<value<< "added"<<endl;

}
int linklist::length_list() {
    int len = 0;
    node* tmp = head;


    while(tmp->show_next() != NULL){
        tmp = tmp->show_next();
        len = len+1;

    }

    return len+1;

}

void linklist::del(int value) {

    node* tmp = head;
    node* prev;

  while(tmp->show_next() != NULL)
  {
      if(tmp->show_value() == value)
      {
          if(head->show_value() == tmp->show_value())
          {
              head = head->show_next();
          }

          else{

              prev->set_next(tmp->show_next());

          }


          delete tmp;
          break;
      }
      else{
          prev=tmp;

          tmp = tmp->show_next();
      }
  }
    if(tmp->show_next() == NULL and tmp->show_value() == value)
    {
        if(head->show_next() == NULL and head->show_value() == value)
        {
            head = NULL;
            delete tmp;
        }

        else        {

            prev->set_next(tmp->show_next());
            delete tmp;
        }
    }


}

void linklist::display_node() {

    node* tmp = head;

    while(tmp->show_next() != NULL)
    {
        std::cout << tmp->show_value()<<endl;
        tmp = tmp->show_next();
    }

    std::cout << tmp->show_value()<<endl;




}
int main(){
    linklist list;
    list.add_node(10);
    list.add_node(20);
    list.add_node(30);
    list.add_node(40);
    list.add_node(50);
    list.display_node();
    int size = list.length_list();
    cout<<size<<endl;
    list.del(30);
    list.display_node();
     size = list.length_list();
    cout<<size<<endl;

}

Thursday, February 23, 2017

Bellman-ford algorithm implementation in Java, and C

Bellman Ford algorithm is an algorithm of finding shortest path in a graph from the given source.

let us take an example of a graph:


Source Code in C:

#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <limits.h>
struct Edge
{
int src,dst,wt;
};

struct Graph
{
int V,E;
struct Edge *edge;

};

void printArr(int dist[], int n)
{
    printf("Vertex   Distance from Source\n");
    for (int i = 0; i < n; ++i)
        printf("%d \t\t %d\n", i, dist[i]);
}

void BellmanFord(struct Graph* graph, int src)
{
    int V = graph->V;
    int E = graph->E;
    int dist[V];

    // Step 1: Initialize distances from src to all other vertices
    // as INFINITE
    for (int i = 0; i < V; i++)
        dist[i]   = INT_MAX;
    dist[src] = 0;

  
    for (int i = 1; i <= V-1; i++)
    {
        for (int j = 0; j < E; j++)
        {
            int u = graph->edge[j].src;
            int v = graph->edge[j].dst;
            int weight = graph->edge[j].wt;
            if (dist[u] != INT_MAX && dist[u] + weight < dist[v])
                dist[v] = dist[u] + weight;
        }
    }

   
    for (int i = 0; i < E; i++)
    {
        int u = graph->edge[i].src;
        int v = graph->edge[i].dst;
        int weight = graph->edge[i].wt;
        if (dist[u] != INT_MAX && dist[u] + weight < dist[v])
            printf("Graph contains negative weight cycle");
    }

    printArr(dist, V);

    return;
}

int main()
{
   printf(" this is the first program\n");
   int vertex =5;
   int edge =8;
   struct Graph *graph = (struct Graph *)malloc(sizeof(struct Graph));
   graph->V = vertex;
   graph->E = edge;
   graph->edge= (struct Edge*) malloc( graph->E * sizeof( struct Edge ) );


   //add the node for vertex A -B
   graph->edge[0].src = 0;
   graph->edge[0].dst = 1;
   graph->edge[0].wt = -1;


    //add the node for vertex A-C
   graph->edge[1].src = 0;
   graph->edge[1].dst = 2;
   graph->edge[1].wt = 4;
   
      //add the node for vertex B-C
   graph->edge[2].src = 1;
   graph->edge[2].dst = 2;
   graph->edge[2].wt = 3;

      //add the node for vertex B-D
   graph->edge[3].src = 1;
   graph->edge[3].dst = 4;
   graph->edge[3].wt = 2;


      //add the node for vertex  B-E
   graph->edge[4].src = 0;
   graph->edge[4].dst = 1;
   graph->edge[4].wt = -1;


      //add the node for vertex E-D
   graph->edge[5].src = 4;
   graph->edge[5].dst = 3;
   graph->edge[5].wt = -3;


      //add the node for vertex D-B
   graph->edge[6].src = 3;
   graph->edge[6].dst = 1;
   graph->edge[6].wt = 1;


      //add the node for vertex D-C
   graph->edge[7].src = 3;
   graph->edge[7].dst = 2;
   graph->edge[7].wt = 5;  

   BellmanFord(graph, 0);

    return 0;



}



Source Code in Java:

/** * Created by laxmikadariya on 2/15/17. */
import java.util.*;
import java.lang.*;
import java.io.*;


class Graph{

    int V,E;

    class Edge{
        int src, dst,wt;
        Edge(){
            src=dst=wt=0;
        }


    }
    Edge edge[];

    Graph(int v,int e)
    {
        V=v;
        E=e;
        edge = new Edge[e];
        for (int i=0;i<e;i++)
        {
            edge[i]=new Edge();
        }


    }

    void BellmanFord(Graph graph,int src)
    {
        int V = graph.V, E = graph.E;
        int dist[] = new int[V];

              for (int i=0; i<V; ++i)
            dist[i] = Integer.MAX_VALUE;
        dist[src] = 0;

         for (int i=1; i<V; ++i)
        {
            for (int j=0; j<E; ++j)
            {
                int u = graph.edge[j].src;
                int v = graph.edge[j].dst;
                int weight = graph.edge[j].wt;
                if (dist[u]!=Integer.MAX_VALUE &&
                        dist[u]+weight<dist[v])
                    dist[v]=dist[u]+weight;
            }
        }

       
        for (int j=0; j<E; ++j)
        {
            int u = graph.edge[j].src;
            int v = graph.edge[j].dst;
            int weight = graph.edge[j].wt;
            if (dist[u]!=Integer.MAX_VALUE &&
                    dist[u]+weight<dist[v])
                System.out.println("Graph contains negative weight cycle");
        }
        System.out.println("Vertex   Distance from Source");
        for (int i=0; i<V; ++i)
            System.out.println(i+"\t\t"+dist[i]);
    }


}
public class bellmon_ford {


    public static void main(String[] args) {
        int V = 5;
        int E = 8;
        Graph graph =  new Graph(V,E);



        //add the node for vertex A -B        
        graph.edge[0].src=0;
        graph.edge[0].dst = 1;
        graph.edge[0].wt = -1;


        //add the node for vertex A-C       
        graph.edge[1].src = 0;
        graph.edge[1].dst = 2;
        graph.edge[1].wt = 4;

        //add the node for vertex B-C        
        graph.edge[2].src = 1;
        graph.edge[2].dst = 2;
        graph.edge[2].wt = 3;

        //add the node for vertex B-D       
         graph.edge[3].src = 1;
        graph.edge[3].dst = 4;
        graph.edge[3].wt = 2;


        //add the node for vertex  B-E       
        graph.edge[4].src = 0;
        graph.edge[4].dst = 1;
        graph.edge[4].wt = -1;


        //add the node for vertex E-D        
        graph.edge[5].src = 4;
        graph.edge[5].dst = 3;
        graph.edge[5].wt = -3;


        //add the node for vertex D-B        
        graph.edge[6].src = 3;
        graph.edge[6].dst = 1;
        graph.edge[6].wt = 1;


        //add the node for vertex D-C        
        graph.edge[7].src = 3;
        graph.edge[7].dst = 2;
        graph.edge[7].wt = 5;

        graph.BellmanFord(graph, 0);



    }
}


Thursday, February 9, 2017

Reversing each word of the string with blank space preserved in Python and Java

we can come in the situation that we need to reverse each word of the string and also we need to preserve the blank space i.e we may have more than one space character in between each word and that needs to be preserved as well. Here I have mentioned the code for Python and Java.

Input:   "   I         am Laxmi     Kadariya"
Output:     I         ma imxaL     ayiradaK 

Algorithm:
1) split the string in to words:
2) reverse each word
3) finally join all the reverse word with space
def rev_string(test):
 final_str = ''
 words = test.split(' ')
 for x in words:
  rev_word = x[::-1]
  final_str = final_str + rev_word + ' ' 

 print final_str


 
  



if __name__ == '__main__':
 test = "   I         am Laxmi     Kadariya"
 rev_string(test)

Java Code:

/**
 * Created by laxmikadariya on 2/8/17.
 */
public class string_rev {
    static void reverseEachWordOfString(String inputString)
    {
        String[] words = inputString.split(" ");

        String reverseString = "";

        for (int i = 0; i < words.length; i++)
        {
            String word = words[i];


            String reverseWord = "";

            for (int j = word.length()-1; j >= 0; j--)
            {
                reverseWord = reverseWord + word.charAt(j);
            }

            reverseString = reverseString + reverseWord + " ";
        }

        System.out.println(inputString);

        System.out.println(reverseString);

        System.out.println("-------------------------");
    }

    public static void main(String[] args)
    {
        reverseEachWordOfString("   I am     Laxmi Kadariya");

    }
}


Saturday, January 28, 2017

Finding the LCM and GCD of multiple numbers in python


Finding GCD of Multiple numbers:

#!/usr/bin/python



# finding gcd for two numbers

def gcd(x, y):

    while y != 0:

        (x, y) = (y, x % y)

    return x
if __name__ == '__main__':
 numbers= []
 count = input("how many numbers")
 for i in range (0, count):
  number = input("enter the number %d  " %(i+1))
  numbers.append(number)
 sorted_num = sorted(numbers)
 gcd_val = sorted_num[0]

 for i in range(1,count):
  gcd_val = gcd(gcd_val,sorted_num[i])


print "gcd value= %d" %gcd_val
Finding LCM values

def lcm(x, y):
   """This function takes two
   integers and returns the L.C.M."""

   # choose the greater number
   if x > y:
       greater = x
   else:
       greater = y

   while(True):
       if((greater % x == 0) and (greater % y == 0)):
           lcm = greater
           break
       greater += 1

   return lcm


if __name__ == '__main__':
  numbers= []
  count = input("how many numbers")
  for i in range (0, count):
    number = input("enter the number %d  " %(i+1))
    numbers.append(number)
 
  lcm_val = numbers[0]

  for i in range(1,count):
    lcm_val = lcm(lcm_val,numbers[i])


print "lcm value= %d" %lcm_val



Sunday, January 8, 2017

Stack and Queue Implementation in C++

Implementation of Stack in C++

#include<iostream>

#include<cstdlib>

#define MAX_SIZE 20

using namespace std;

class Stack{

    private:

        int item[MAX_SIZE];

        int top;

    public:

        Stack(){

            top = -1;

        }

        void push(int data){

            item[++top] = data;

        }

        int pop(){

            return item[top--];

        }

        int size(){

            return top+1;

        }

        bool is_empty(){

            if(top==-1)

                return true;

            else

                return false;

        }

        bool is_full(){

            if(top==MAX_SIZE-1)

                return true;

            else

                return false;

        }

        void display(){

            for(int i=0; i<this->size(); i++){

                cout<<item[i]<<" ";

            }

            cout<<endl;

        }

};

int main(){

    int input;

    int temp;

    Stack stack;

    while(true){



        cout<<"Choose any one of the following"<<endl;

        cout<<"1. Push Item. "<<endl;

        cout<<"2. Pop Item."<<endl;



        cout<<"3. Display all elements of stack."<<endl;

        cout<<"4. Size of Stack."<<endl;

        cout<<"5. Exit."<<endl;

        cout<<"Your Choice: ";

        cin>>input;

        switch(input){

            case 1:

                if(!stack.is_full()){

                    cout<<"Enter number to push: ";

                    cin>>temp;

                    stack.push(temp);

                }else{

                    cout<<"Can't push. Stack is Full!!"<<endl;

                }

                break;

            case 2:

                if(!stack.is_empty()){

                    cout<<"The number popped is: "<<stack.pop()<<endl;

                }else{

                    cout<<"Cant't pop. Stack is Empty!!"<<endl;

                }

                break;



            case 3:

                if(!stack.is_empty()){

                    cout<<"The elements in stack are: ";

                    stack.display();

                    cout<<endl;

                }else{

                    cout<<"Stack is Empty"<<endl;

                }

                break;



            case 4:

                cout<<"The size of the stack is: "<<stack.size()<<endl;

                break;



            case 5:

                exit(0);

                break;

        }

    }

    return 0;

}
Implementation of Queue in C++



#include<iostream>

#define Maxsize 10

using namespace std;

class Queue

{



    private:

       int front;

       int rear;

       int queue[Maxsize];

    public:

       Queue()

       {

           front=0;

           rear=-1;

       }

       void enqueue()

       {

           int data;

           cout<<"Enter data to enqueue :";cin>>data;

           if(rear==Maxsize-1)

              cout<<"Queue is FULL .\n";

            else

              queue[++rear]=data;

       }

       int dequeue()

       {

           if(front>rear)

             cout<<"Queue is EMPTY .\n";

            else

              {

                  int data=queue[front];

                  return data;

              }

       }

       void display()

       {

           for(int i=0;i<=rear;i++)

             cout<<queue[i]<<endl;

       }



};

int main()

{

    Queue q;

    int res;

    char choice;

    cout<<"\n\tQueue Operation :\n\n";

    cout<<"\n1.Enqueue \n";

    cout<<"2.Dequeue \n";

    cout<<"3.Display\n";

    do{

    cout<<"Enter your choice :1/2/3   :: ";

    cin>>res;

    switch(res)

    {

        case 1:q.enqueue();break;

        case 2:q.dequeue();break;

        case 3:q.display();

    }

    cout<<"Want to continue ? ";cin>>choice;

    }while(choice=='y');

   return 0;

}