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;

}





Monday, October 24, 2016

creating a function for finding ancestor in oracle from parent-child table

when we have a table as

parent        child

A            B
B            C
C           D


then here the ancestor of (D) is to be found as
C
B
A

Thus finding such result from the table can be easily done in database through the use of hierarchial query

SELECT parent FROM ancestor START WITH child = 'D' CONNECT BY PRIOR parent = child;

this query can directly qive us the result as oracle has the feature of hierarchical query . So The function in pl/sql can be written as:

create or replace FUNCTION find_ancestor(in_cname IN varchar2) 
return varchar2

AS 
    stat varchar2(50);


CURSOR anc_cur IS 
SELECT parent FROM ancestor START WITH child = in_cname CONNECT BY PRIOR parent = child;
anc_rec anc_cur%ROWTYPE;
indx number := 0;

BEGIN
open anc_cur;

dbms_output.put_line('-------ancestors  of ----------' || in_cname);
loop
fetch anc_cur into anc_rec;

if anc_cur%NOTFOUND
then
exit;
else
   -- return anc_rec.parent;
dbms_output.put_line(''||anc_rec.parent);


end if;
end loop;
close anc_cur;
stat := '-----success---------';
return stat;


END find_ancestor;

/

now the result can be obtained with query  as 
select find_ancestor('D') from dual;


now we can also write the function without using this in built query but using recursion and cursor as:

create or replace FUNCTION find_ancestor(in_cname IN varchar2) 
return varchar2

AS 
    stat varchar2(50);


CURSOR anc_cur IS 
SELECT parent FROM ancestor  where child = in_cname;
anc_rec anc_cur%ROWTYPE;
indx number := 0;

BEGIN
open anc_cur;

-- dbms_output.put_line('-------ancestors  of ----------' || in_cname);
loop
fetch anc_cur into anc_rec;

if anc_cur%NOTFOUND
then

            -- dbms_output.put_line('inside cursor exit');
exit;
else

         stat:= find_ancestor(anc_rec.parent);
   -- return anc_rec.parent;
dbms_output.put_line(''||anc_rec.parent);



end if;
end loop;

close anc_cur;
    stat:= '----success---';

return stat;


END find_ancestor;
/

here the same query can bewritten and the result is same but here we have used recursion to find the parent.

Python script to run the bash script file

we can run the  script file or executable file from the progamming just simply by ./script_file name . Sometimes we may reach in to the situation that we need to run through the python program. so inorder to run the script from python file can be easily done through  subprocess  of python.

The scenario of this program is at a certain location, I have several folder  like A,B,C, D and so on and each folder has the executable files. I need to run each of them. And to do so I can go to each folder and run the executable, however this is tedious. thus This is the program which runs the executable files from the each folder.


import os
import subprocess
rootdir = '/home/laxmi/Desktop/assembler/assignment_grad/assign3/grade'

for subdir, dirs, files in os.walk(rootdir):
    for file in dirs:
        path = os.path.join(subdir, file)
        # print file
        # abspath = os.path.abspath(__file__)
        # print abspath
        # dname = os.path.dirname(abspath)
        # print dname
        os.chdir(path)
        print " --------entering folder------"
        print "%s"%path
        subprocess.call('./asm64 *.asm',shell=True)