Saturday, 11 April 2015

Generic Representation of Graph - Generic List of Vertices and Edges

LinkedList_Generic.h
struct LinkedList_Generic
{
 struct ListNode_Generic*start;
 int elementSize;
 /*
  elementSize, will store the size of each element. 
  The element size is important, because generics in C are limited to void pointers, 
  in order to let the compiler know the amount of memory needed by malloc/memcpy. 
  This information should always be supplied dynamically. The caller should use sizeof(int) rather than 4.
 */
};
struct ListNode_Generic
{
 void *data;
 struct ListNode_Generic*next;
};
struct LinkedList_Generic *makeAndInitialiseLinkedList();
struct ListNode_Generic *makeAndInitialiseListNode(struct LinkedList_Generic *list,void*element);
void addElement(struct LinkedList_Generic*list,struct ListNode_Generic*element);
void removeElement(struct LinkedList_Generic*list,struct ListNode_Generic*node);
struct ListNode_Generic*getNodeReferenceWithGivenData(struct LinkedList_Generic*list,void*data);



LinkedList_Generic.c
#include<stdlib.h>
#include<string.h>
#include"LinkedList_Generic.h"

struct LinkedList_Generic *makeAndInitialiseLinkedList(int elementSize)
{
 struct LinkedList_Generic *list;
 list=(struct LinkedList_Generic*)malloc(sizeof(struct LinkedList_Generic));
 list->start=NULL;
 list->elementSize=elementSize;
 return list;
}
struct ListNode_Generic *makeAndInitialiseListNode(struct LinkedList_Generic *list,void*element)
{
 struct ListNode_Generic*listNode;
 listNode=(struct ListNode_Generic*)malloc(sizeof(struct ListNode_Generic));
 listNode->data=element;
 //listNode->data=malloc(sizeof(list->elementSize));
 //memcpy(listNode->data,element,list->elementSize);
 listNode->next=NULL;
 return listNode;
}
void addElement(struct LinkedList_Generic*list,struct ListNode_Generic*element)
{
 struct ListNode_Generic*ptr,*prev;
 if((list->start)==NULL)
  (list->start)=element;
 else
 {
  for(ptr=(list->start);ptr;prev=ptr,ptr=ptr->next);
  (prev->next)=element;
 }
}
void removeElement(struct LinkedList_Generic*list,struct ListNode_Generic*node)
{
 struct ListNode_Generic*ptr,*prev;
 for(ptr=(list->start),prev=NULL;ptr && (ptr)!=node;prev=ptr,ptr=ptr->next);
 if(ptr)
 {
  if(prev!=NULL)
  {
   prev->next=ptr->next;
   if(ptr)
   {
    free(ptr);
   }
  }
  else if(prev==NULL && ptr!=NULL) // means the element that we need to delete is the start of the list.
  {
   prev=list->start;
   (list->start)=((list->start)->next);
   if(prev)
   {
    free(prev);
   }
  }
 }
}
struct ListNode_Generic*getNodeReferenceWithGivenData(struct LinkedList_Generic*list,void*data)
{
 struct ListNode_Generic*node;
 for(node=list->start;node;node=node->next)
 {
  if((node->data)==data)
   return node;
 }
}



Graph_Generic.h
struct Graph_Generic
{
 struct LinkedList_Generic *vertexList,*edgeList;
 int numberOfVertices, numberOfEdges;
};
struct Vertex
{
 int id;
 int inDegree,outDegree;
};
struct Edge
{
 int id,sourceVertex,destinationVertex,isDirected,weight;
};
struct Graph_Generic*makeAndInitialiseGraph();
void addVertex(struct Graph_Generic*graph,struct Vertex*vertex);
void removeVertex(struct Graph_Generic*graph,int vertexNumber);
void addEdge(struct Graph_Generic*graph,struct Edge*edge);
void removeEdge(struct Graph_Generic *graph,int ,int ,int);
struct Edge *makeEdge(int sourceVertex,int destinationVertex,int weight,int isDirected);
struct Vertex *makeVertex();
void printGraph_Generic(struct Graph_Generic*grpah);



Graph_Generic.c
#include"Graph_Generic.h"
#include"LinkedList_Generic.h"
#include<stdlib.h>
#include<stdio.h>
struct Graph_Generic*makeAndInitialiseGraph()
{
 struct Graph_Generic*graph;
 graph=(struct Graph_Generic*)malloc(sizeof(struct Graph_Generic));
 graph->numberOfVertices=0;
 graph->numberOfEdges=0;
 graph->vertexList=makeAndInitialiseLinkedList(sizeof(struct Vertex));
 graph->edgeList=makeAndInitialiseLinkedList(sizeof(struct Edge));
 return graph;
}
struct Edge *makeEdge(int sourceVertex,int destinationVertex,int weight,int isDirected)
{
 static int edgeNumber=0;
 struct Edge*edge;
 edge=(struct Edge*)malloc(sizeof(struct Edge));
 edge->sourceVertex=sourceVertex;
 edge->destinationVertex=destinationVertex; 
 edge->weight=weight;
 edge->isDirected=isDirected;
 edge->id=edgeNumber++;
 return edge;
}
struct Vertex *makeVertex()
{
 static int vertexNumber=0;
 struct Vertex*vertex;
 vertex=(struct Vertex*)malloc(sizeof(struct Vertex));
 (vertex->id)=vertexNumber++;
 return vertex;
}

void addVertex(struct Graph_Generic*graph,struct Vertex*vertex)
{
 (graph->numberOfVertices)++;
 addElement(graph->vertexList,makeAndInitialiseListNode(graph->vertexList,vertex));
}
void removeVertex(struct Graph_Generic*graph,int vertexNumber)
{
 struct Edge*e;
 struct ListNode_Generic*ptr,*ptr1;
 (graph->numberOfVertices)--;
 for(ptr=graph->vertexList->start;ptr;ptr=ptr->next)
 {
  if(((struct Vertex*)(ptr->data))->id==vertexNumber)
   break;
 }
 if(ptr)
 {
  /*
   when you will be deleting an vertex then all the edges from and to that vertex should be deleted.
  */
  for(ptr1=graph->edgeList->start;ptr1;ptr1=ptr1->next)
  {
   e=(struct Edge*)(ptr1->data);
   if(e->sourceVertex==vertexNumber || e->destinationVertex==vertexNumber)
    removeEdge(graph,e->sourceVertex,e->destinationVertex,e->weight);
  }
  removeElement(graph->vertexList,ptr);
 }
}
void addEdge(struct Graph_Generic*graph,struct Edge*edge)
{
 (graph->numberOfEdges)++;
 addElement(graph->edgeList,makeAndInitialiseListNode(graph->edgeList,edge));
}
void removeEdge(struct Graph_Generic *graph,int sourceVertex,int destinationVertex,int weight)
{
 struct ListNode_Generic*ptr;
 (graph->numberOfEdges)--;
 for(ptr=(graph->edgeList->start);ptr;ptr=ptr->next)
 {
  if(
   ((struct Edge*)(ptr->data))->sourceVertex==sourceVertex &&
   ((struct Edge*)(ptr->data))->destinationVertex==destinationVertex &&
   ((struct Edge*)(ptr->data))->weight==weight
  ) break;
 }
 if(ptr)
  removeElement(graph->edgeList,ptr);
}
void printGraph_Generic(struct Graph_Generic*graph)
{
 int i;
 struct ListNode_Generic*ptr;
 printf("\nPrinting the vertex List : \n");
 printf("\nTotal Number Of Vertices in the Graph : %d\n",graph->numberOfVertices);
 for(ptr=(struct ListNode_Generic*)((graph->vertexList)->start);ptr;ptr=ptr->next)
  printf("%d ",((struct Vertex*)(ptr->data))->id);
 printf("\nTotal Number Of Edges in the Graph : %d\n",graph->numberOfEdges);
 for(ptr=(struct ListNode_Generic*)((graph->edgeList)->start);ptr;ptr=ptr->next)
  printf("Edge No. : %d, from %d to %d with weight=%d and isDirected?=%d\n",((struct Edge*)(ptr->data))->id,((struct Edge*)(ptr->data))->sourceVertex,((struct Edge*)(ptr->data))->destinationVertex,((struct Edge*)(ptr->data))->weight,((struct Edge*)(ptr->data))->isDirected);
}



main.c
#include<stdio.h>
#include"Graph_Generic.h"
int main()
{
 struct Graph_Generic*graph;
 int a,b,weight,isDirected,i,numberOfVertices,numberOfEdges,sourceVertex,destinationVertex,vertexNumber;

 printf("Enter the number of Vertices in the Graph : ");
 scanf("%d",&(numberOfVertices));
 printf("Enter the number of Edges in the Graph : ");
 scanf("%d",&(numberOfEdges));

 graph=makeAndInitialiseGraph();

 for(i=0;i<numberOfVertices;i++)
  addVertex(graph,makeVertex());

 printf("NOTE 1 : The ordering of the Vertices and Edges is zero indexed.\n");
 printf("NOTE 2 : For each edge enter the following in Sequence : \n");
 printf("\t1. Source Vertex Number.\n");
 printf("\t2. Destination Vertex Number.\n");
 printf("\t3. Weight associated with Edge.\n");
 printf("\t4. 1 if the Edge is Directed, and 0 otherwise.\n");
 
 for(i=0;i<numberOfEdges;i++)
 {
  printf("Enter the edge Number %d : ",i+1);
  scanf("%d%d%d%d",&a,&b,&weight,&isDirected);
  addEdge(graph,makeEdge(a,b,weight,isDirected));
 }
 printGraph_Generic(graph);
 
 printf("\nDeleting an Edge : \n");
 printf("Enter the sourceVertex, destinationVertex and weight of the graph : ");
 scanf("%d%d%d",&sourceVertex,&destinationVertex,&weight);
 removeEdge(graph,sourceVertex,destinationVertex,weight);
 
 printf("Deleting a Vertex : \n");
 printf("Enter the Vertex number to be deleted : ");
 scanf("%d",&vertexNumber);
 removeVertex(graph,vertexNumber);
 
 printGraph_Generic(graph);
 
 printf("Program Execution Successful...\n");
 return 0;
}



Makefile
all: LinkedList_Generic.o Graph_Generic.o main.o
 gcc LinkedList_Generic.o Graph_Generic.o main.o -o hello
LinkedList_Generic.o: LinkedList_Generic.c
 gcc -c LinkedList_Generic.c
Graph_Generic.o: Graph_Generic.c
 gcc -c Graph_Generic.c
main.o: main.c
 gcc -c main.c
clean:
 rm -rf *.o *~ hello



SampleInputData.txt
6
9
1 0 1 1
1 3 1 1
1 2 1 1 
0 5 1 1
0 4 1 1
2 3 1 1
2 4 1 1
2 5 1 1
4 3 1 1
2 5 1
0



Adjacency Matrix Representation of Graph

one_D_bit_array.h
int get_one_D_bit_array(int ,int *);
void reset_one_D_bit_array(int ,int *);
void set_one_D_bit_array(int ,int *);


one_D_bit_array.c
#include"one_D_bit_array.h"
int get_one_D_bit_array(int i,int* arr)
{
 if((arr[i/32]&((unsigned int)1<<(31-i%32)))!=0)
  return 1;
 return 0;
}
void set_one_D_bit_array(int i,int *arr)
{
 arr[i/32]|=((unsigned int)1<<(31-i%32));  // to set its 31-(n%32) th bit.
}
void reset_one_D_bit_array(int i,int *arr)
{
 arr[i/32]&=(~((unsigned int)1<<(31-i%32))); // to reset its 31-(n%32) th bit.
}



two_D_bit_array.h
int get_two_D_bit_array(int ,int ,int *,int);
void set_two_D_bit_array(int ,int ,int *,int);
void reset_two_D_bit_array(int ,int ,int *,int);



two_D_bit_array.c
#include"two_D_bit_array.h"

/*  
  this function will return bit value in 
  ith row and 
  jth column
  from the array 'arr'
  which provides an abstraction of 2-D bit array of size n * n.
*/ 
int get_two_D_bit_array(int i,int j,int* arr,int n)
{
 int bitNumber=i*n+j;
 if((arr[bitNumber/32]&((unsigned int)1<<(31-bitNumber%32)))!=0)
  return 1;
 return 0;
}

/*  
  this function will set the bit value in 
  ith row and 
  jth column
  in the array 'arr'
  which provides an abstraction of 2-D bit array of size n * n
  to 1.
*/ 
void set_two_D_bit_array(int i,int j,int *arr,int n)
{ 
 int bitNumber=i*n+j;
 arr[bitNumber/32]|=((unsigned int)1<<(31-bitNumber%32));  // to set its 31-(bitNumber%32) th bit.
}

/*  
  this function will set the bit value in 
  ith row and 
  jth column
  in the array 'arr'
  which provides an abstraction of 2-D bit array of size n * n
  to 0.
*/ 
void reset_two_D_bit_array(int i,int j,int *arr,int n)
{
 int bitNumber=i*n+j;
 arr[bitNumber/32]&=(~((unsigned int)1<<(31-bitNumber%32))); // to reset its 31-(bitNumber%32) th bit.
}


Graph_AdjacencyMatrix.h
struct Graph
{
 int numberOfVertices,numberOfEdges;
 unsigned int*adjacencyMatrix;
};
struct Graph*makeNewGraph();
void initializeAdjacencyMatrix(struct Graph*);
void createEdge(struct Graph*,int,int);
void removeEdge(struct Graph*,int,int);
void showAdjacencyMatrix(struct Graph*);
int findNumberOfComponents(struct Graph*);



Graph_AdjacencyMatrix.c
#include<stdio.h>
#include<stdlib.h>
#include"Graph_AdjacencyMatrix.h"
#include"two_D_bit_array.h"
#include"one_D_bit_array.h"

struct Graph*makeNewGraph()
{
 struct Graph*g;
 g=(struct Graph*)malloc(sizeof(struct Graph));
 return g;
}
void initializeAdjacencyMatrix(struct Graph*g)
{
 /*
  The adjacencyMatrix corresponding to vertex u and v will contain 1 if there is an edge from u to v
  otherwise it will contain 0

  Description of data structure used for making adjacencyMatrix:
   * We will need n*n bits to represent the existence of an edge between two vertices
   * These n*n bits should be assumed to be arranged in the linear fashion
   * For implementing this linear fashion we will use an array of integers.
   * For a standard 32 bit compiler (like gcc 4.8.2) size of an integer is 32 bits (4 bytes).
   * By this linear arrangement of AdjacencyMatrix we will optimally exploit every single bit.
 */
 int sizeOfIntegerColumns,i,j;
 sizeOfIntegerColumns=((g->numberOfVertices)*(g->numberOfVertices))/32+1;
 (g->adjacencyMatrix)=(unsigned int*)malloc(sizeof(unsigned int)*sizeOfIntegerColumns);
 for(i=0;i<sizeOfIntegerColumns;i++)
  (g->adjacencyMatrix)[i]=0;
}
void createEdge(struct Graph*g,int a,int b)
{
 set_two_D_bit_array(a,b,g->adjacencyMatrix,g->numberOfVertices);
}
void removeEdge(struct Graph*g,int a,int b)
{
 reset_two_D_bit_array(a,b,g->adjacencyMatrix,g->numberOfVertices);
}
void showAdjacencyMatrix(struct Graph*g)
{
 int i,j,bitNumber;
 printf("The adjacency Matrix of the Graph is as follows : \n");
 for(i=0;i<(g->numberOfVertices);i++)
 {
  for(j=0;j<(g->numberOfVertices);j++)
   printf("%d",get_two_D_bit_array(i,j,g->adjacencyMatrix,g->numberOfVertices));
  printf("\n");
 }
}

int findNumberOfComponents(struct Graph*g)
{
 /*
  first of all we need to create a copy of the AdjacencyMatrix.
 */
 unsigned int *adjacencyMatrix_copy,*flag,sizeOfIntegerColumns,i,j,k,components;
 sizeOfIntegerColumns=((g->numberOfVertices)*(g->numberOfVertices))/32+1;
 adjacencyMatrix_copy=(unsigned int*)malloc(sizeof(unsigned int)*sizeOfIntegerColumns);
 for(i=0;i<sizeOfIntegerColumns;i++)
  adjacencyMatrix_copy[i]=(g->adjacencyMatrix)[i];
 /* copy of adjacencyMatrix created */

 /*  now we need to keep the track of vertices being merged
  for this we need to introduce a one-D bit array that will keep track of this information.
  let this one-D bit array be flag.
 */
 flag=(unsigned int *)malloc(sizeof(unsigned int)*(g->numberOfVertices)/32+1);
 for(i=0;i<(g->numberOfVertices)/32+1;i++)
  flag[i]=0;
 /*
  if the nth bit of flag array is 0 this means that the vertex with vertexNumber 'n' is still
  alive and is not merged with any other vertex.

  if the nth bit of flag array is 1 this means that the vertex with vertexNumber 'n' is dead
  and is merged with some other vertex and has no existence now.
 */
 /* now we are ready for merging vertices in our dummy (copied) adjacencyMatrix.  */
 for(i=0;i<(g->numberOfVertices);i++)
 {
  if(get_one_D_bit_array(i,flag)==0) // means ith vertex is alive
  {
   for(j=0;j<(g->numberOfVertices);j++)
   {
    if(j!=i && get_one_D_bit_array(j,flag)==0) // means the jth vertex is alive
    {
     if(get_two_D_bit_array(i,j,adjacencyMatrix_copy,g->numberOfVertices)==1)
     {
      /*
       now we need to merge the ith node with the jth node
       for this we need to merge
        ith row with jth row, and
        ith col with jth col
      */
      for(k=0;k<(g->numberOfVertices);k++) // merging the ith and jth rows
      {
       if(get_two_D_bit_array(i,k,adjacencyMatrix_copy,g->numberOfVertices) | get_two_D_bit_array(j,k,adjacencyMatrix_copy,g->numberOfVertices))
        set_two_D_bit_array(i,k,adjacencyMatrix_copy,g->numberOfVertices);
      }
      for(k=0;k<(g->numberOfVertices);k++) // merging the ith and jth cols
      {
       if(get_two_D_bit_array(k,i,adjacencyMatrix_copy,g->numberOfVertices) | get_two_D_bit_array(k,j,adjacencyMatrix_copy,g->numberOfVertices))
        set_two_D_bit_array(k,i,adjacencyMatrix_copy,g->numberOfVertices);
      }
      /* now the jth vertex is merged with ith vertex so the ith vertex should have no existence */
      /* so we need to set the jth bit of flag array to 1 */
      set_one_D_bit_array(j,flag); // declaring that the jth vertex is now dead.
     }
    }
   }
  }
 }
 /* 
  now the total number of components in the graph will be the number of vertices that still have zero 
  correponding to their vertex number in flag array.
 */
 components=0;
 for(i=0;i<(g->numberOfVertices);i++)
  if(get_one_D_bit_array(i,flag)==0)
   components++;
 return components;
}



main.c
#include<stdio.h>
#include"Graph_AdjacencyMatrix.h"

int main()
{
 int i,n,a,b;
 struct Graph*g;
 g=makeNewGraph();
 printf("Enter the number of Vertices in the Graph : ");
 scanf("%d",&(g->numberOfVertices));
 printf("Enter the number of Edges in the Graph : ");
 scanf("%d",&(g->numberOfEdges));
 initializeAdjacencyMatrix(g);
 printf("NOTE : The ordering of the vertices is zero indexed.\n");
 for(i=0;i<(g->numberOfEdges);i++)
 {
  printf("Enter the edge Number %d : ",i+1);
  scanf("%d%d",&a,&b);
  createEdge(g,a,b);
 }
 showAdjacencyMatrix(g);
 printf("Number of components in the Graph = %d\n",findNumberOfComponents(g));
 printf("\nProgram execution successful...\n");
 return 0;
}


Makefile
all: hello
hello: one_D_bit_array.o two_D_bit_array.o Graph_AdjacencyMatrix.o main.o
 gcc one_D_bit_array.o two_D_bit_array.o Graph_AdjacencyMatrix.o main.o -o hello
one_D_bit_array.o: one_D_bit_array.c
 gcc -c one_D_bit_array.c
two_D_bit_array.o: two_D_bit_array.c
 gcc -c two_D_bit_array.c
main.o: main.c
 gcc -c main.c
graph.o: Graph_AdjacencyMatrix.c
 gcc -c Graph_AdjacencyMatrix.c
clean:
 rm -rf *~ *.o hello



SampleTestData.txt
4
8
0 2
2 0
1 3
3 1
0 3
3 0
3 2
2 3



Adjacency List Representation of Graph

LinkedList_Generic.h

struct LinkedList_Generic
{
 struct ListNode_Generic*start;
 int elementSize;
 /*
  elementSize, will store the size of each element. 
  The element size is important, because generics in C are limited to void pointers, 
  in order to let the compiler know the amount of memory needed by malloc/memcpy. 
  This information should always be supplied dynamically. The caller should use sizeof(int) rather than 4.
 */
};
struct ListNode_Generic
{
 void *data;
 struct ListNode_Generic*next;
};
struct LinkedList_Generic *makeAndInitialiseLinkedList();
struct ListNode_Generic *makeAndInitialiseListNode(struct LinkedList_Generic *list,void*element);
void addElement(struct LinkedList_Generic*list,struct ListNode_Generic*element);
void removeElement(struct LinkedList_Generic*list,struct ListNode_Generic*node);
struct ListNode_Generic*getNodeReferenceWithGivenData(struct LinkedList_Generic*list,void*data);


LinkedList_Generic.c
#include<stdlib.h>
#include<string.h>
#include"LinkedList_Generic.h"

struct LinkedList_Generic *makeAndInitialiseLinkedList(int elementSize)
{
 struct LinkedList_Generic *list;
 list=(struct LinkedList_Generic*)malloc(sizeof(struct LinkedList_Generic));
 list->start=NULL;
 list->elementSize=elementSize;
 return list;
}
struct ListNode_Generic *makeAndInitialiseListNode(struct LinkedList_Generic *list,void*element)
{
 struct ListNode_Generic*listNode;
 listNode=(struct ListNode_Generic*)malloc(sizeof(struct ListNode_Generic));
 listNode->data=element;
 //listNode->data=malloc(sizeof(list->elementSize));
 //memcpy(listNode->data,element,list->elementSize);
 listNode->next=NULL;
 return listNode;
}
void addElement(struct LinkedList_Generic*list,struct ListNode_Generic*element)
{
 struct ListNode_Generic*ptr,*prev;
 if((list->start)==NULL)
  (list->start)=element;
 else
 {
  for(ptr=(list->start);ptr;prev=ptr,ptr=ptr->next);
  (prev->next)=element;
 }
}
void removeElement(struct LinkedList_Generic*list,struct ListNode_Generic*node)
{
 struct ListNode_Generic*ptr,*prev;
 for(ptr=(list->start),prev=NULL;ptr && (ptr)!=node;prev=ptr,ptr=ptr->next);
 if(ptr)
 {
  if(prev!=NULL)
  {
   prev->next=ptr->next;
   if(ptr)
   {
    free(ptr);
   }
  }
  else if(prev==NULL && ptr!=NULL) // means the element that we need to delete is the start of the list.
  {
   prev=list->start;
   (list->start)=((list->start)->next);
   if(prev)
   {
    free(prev);
   }
  }
 }
}
struct ListNode_Generic*getNodeReferenceWithGivenData(struct LinkedList_Generic*list,void*data)
{
 struct ListNode_Generic*node;
 for(node=list->start;node;node=node->next)
 {
  if((node->data)==data)
   return node;
 }
}


Graph_AdjacencyList.h
#include"LinkedList_Generic.h"
struct Graph_AdjacencyList
{
 struct LinkedList_Generic *vertexList;
 int numberOfVertices;
};
struct Vertex_AdjacencyList
{
 int id;
 struct LinkedList_Generic *adjacencyList;
};
struct Graph_AdjacencyList*makeAndInitialiseGraph();
void addVertex(struct Graph_AdjacencyList*graph,struct Vertex_AdjacencyList*vertex);
int getVertexId(struct ListNode_Generic*node);
void removeVertex(struct Graph_AdjacencyList*graph,int vertexNumber);
void addEdge(struct Graph_AdjacencyList*graph,int sourceVertexNumber,int destinationVertexNumber);
void removeEdge(struct Graph_AdjacencyList *graph,int sourceVertexNumber,int destinationVertexNumber);
struct Vertex_AdjacencyList *makeVertex();
void printGraph_AdjacencyList(struct Graph_AdjacencyList*graph);



Graph_AdjacencyList.c
/*
 This representation of graph is the Adjacency List representation.
 Corresponding to each vertex of the graph we maintain a list of vertices that are connected to that vertex.
 for maintaining the vertex list (adjacency List) corresponding to each vertex, we maintain a Generic List.
 this generic list is defined in LinkedList_Generic.c
 
 this adjacencyList corresponding to each vertex will just store the references of vertex (reference of c, don't get confused with the reference variables of c++)
 
 this storing of reference will have the following advantage :
  Suppose you need to modify any of the data for a specific vertex, then you just need to modify the data correnponding to that vertex in the vertex list.
  you dont need to modify each and every node where this vertex may apper in the adjacencyList of any vertex.
*/

#include"Graph_AdjacencyList.h"
#include<stdlib.h>
#include<stdio.h>
struct Graph_AdjacencyList*makeAndInitialiseGraph()
{
 struct Graph_AdjacencyList*graph;
 graph=(struct Graph_AdjacencyList*)malloc(sizeof(struct Graph_AdjacencyList));
 graph->numberOfVertices=0;
 graph->vertexList=makeAndInitialiseLinkedList(sizeof(struct Vertex_AdjacencyList));
 return graph;
}
struct Vertex_AdjacencyList *makeVertex()
{
 static int vertexNumber=0;
 struct Vertex_AdjacencyList*vertex;
 vertex=(struct Vertex_AdjacencyList*)malloc(sizeof(struct Vertex_AdjacencyList));
 (vertex->id)=vertexNumber++;
 vertex->adjacencyList=makeAndInitialiseLinkedList(sizeof(struct Vertex_AdjacencyList*));
 return vertex;
}
struct Vertex_AdjacencyList*getVertexReference(struct Graph_AdjacencyList*graph,int n)
{
 struct Vertex_AdjacencyList*vertex;
 struct ListNode_Generic*node;
 for(node=graph->vertexList->start;node;node=node->next)
 {
  vertex=(struct Vertex_AdjacencyList*)(node->data);
  if(vertex->id==n)
   return vertex;
 }
}
void addVertex(struct Graph_AdjacencyList*graph,struct Vertex_AdjacencyList*vertex)
{
 (graph->numberOfVertices)++;
 addElement(graph->vertexList,makeAndInitialiseListNode(graph->vertexList,vertex));
}

void removeVertex(struct Graph_AdjacencyList*graph,int vertexNumber)
{
 int i;
 struct ListNode_Generic*node;
 struct Vertex_AdjacencyList*vertex;
 for(node=graph->vertexList->start;node;node=node->next)
 {
  vertex=(struct Vertex_AdjacencyList*)(node->data);
  removeEdge(graph,vertex->id,vertexNumber);
 }
 removeElement(graph->vertexList,getNodeReferenceWithGivenData(graph->vertexList,getVertexReference(graph,vertexNumber)));
}

void addEdge(struct Graph_AdjacencyList*graph,int sourceVertexNumber,int destinationVertexNumber)
{
 addElement
 (
  getVertexReference(graph,sourceVertexNumber)->adjacencyList,
  makeAndInitialiseListNode
  (
   getVertexReference(graph,sourceVertexNumber)->adjacencyList,
   getVertexReference(graph,destinationVertexNumber)
  )
 );
}
void removeEdge(struct Graph_AdjacencyList *graph,int sourceVertexNumber,int destinationVertexNumber)
{
 removeElement
 (
  getVertexReference(graph,sourceVertexNumber)->adjacencyList,
  getNodeReferenceWithGivenData
  (
   getVertexReference(graph,sourceVertexNumber)->adjacencyList,
   getVertexReference(graph,destinationVertexNumber)
  )
 );
}
void printGraph_AdjacencyList(struct Graph_AdjacencyList*graph)
{
 struct Vertex_AdjacencyList*vertexPtr,*jointVertex;
 struct ListNode_Generic*pointer,*ptr;
 int i;
 printf("\nTotal Number Of Vertices in the Graph : %d\n",graph->numberOfVertices);
 printf("\nPrinting the Adjacency List of each vertex. \n");
 for(ptr=(struct ListNode_Generic*)((graph->vertexList)->start);ptr;ptr=ptr->next)
 {
  vertexPtr=(struct Vertex_AdjacencyList*)(ptr->data);
  printf("Vertex No. : %d: ",vertexPtr->id); // Printing the id of current vertex number.
  for(pointer=(struct ListNode_Generic*)((vertexPtr->adjacencyList)->start);pointer;pointer=pointer->next)
  {
   jointVertex=(struct Vertex_AdjacencyList*)(pointer->data);
   printf("%d ",jointVertex->id);
  }
  printf("\n\n");
 }
}


main.c
#include<stdio.h>
#include"Graph_AdjacencyList.h"
int main()
{
 struct Graph_AdjacencyList*graph;
 int a,b,weight,isDirected,i,numberOfVertices,numberOfEdges,sourceVertexNumber,destinationVertexNumber,vertexNumber;

 printf("Enter the number of Vertices in the Graph : ");
 scanf("%d",&(numberOfVertices));
 printf("Enter the number of Edges in the Graph : ");
 scanf("%d",&(numberOfEdges));

 graph=makeAndInitialiseGraph();

 for(i=0;i<numberOfVertices;i++)
  addVertex(graph,makeVertex());

 printf("NOTE 1 : The ordering of the Vertices and Edges is zero indexed.\n");
 printf("NOTE 2 : For each edge enter the following in Sequence : \n");
 printf("\t1. Source Vertex Number.\n");
 printf("\t2. Destination Vertex Number.\n");
 
 for(i=0;i<numberOfEdges;i++)
 {
  printf("Enter the edge Number %d : ",i+1);
  scanf("%d%d",&a,&b);
  addEdge(graph,a,b);
 }
 printGraph_AdjacencyList(graph);
 
 /* Deleting an Edge */
 printf("To Remove an Edge Enter the source and destination vertex number : ");
 scanf("%d%d",&sourceVertexNumber,&destinationVertexNumber);
 removeEdge(graph,sourceVertexNumber,destinationVertexNumber);
 printGraph_AdjacencyList(graph);
 
 /* Deleting a Vertex */
 printf("To delete a vertex enter the vertex number :");
 scanf("%d",&vertexNumber);
 removeVertex(graph,vertexNumber);
 printGraph_AdjacencyList(graph);
 printf("Program Execution Successful...\n");
 return 0;
}


Makefile
all: LinkedList_Generic.o Graph_AdjacencyList.o main.o
 gcc LinkedList_Generic.o Graph_AdjacencyList.o main.o -o hello
LinkedList_Generic.o: LinkedList_Generic.c
 gcc -c LinkedList_Generic.c
Graph_AdjacencyList.o: Graph_AdjacencyList.c
 gcc -c Graph_AdjacencyList.c
main.o: main.c
 gcc -c main.c
clean :
 rm -rf *~ *.o hello


SampleTest.txt
4
8
0 2
2 0
3 0
0 3
2 3
3 2
3 1
1 3

2 0

3

Wednesday, 25 March 2015

FIND THE NUMBER OF COMPONENTS IN A GRAPH : ADJACENCY MATRIX REPRESENTATION - MERGING NODES



Write a program to check whether given graph is connected or not. Compute number of components for disconnected graph.


In graph theory, a connected component (or just component) of an undirected graph is a sub-graph in which any two vertices are connected to each other by paths, and which is connected to no additional vertices in the super-graph.
For example the following graph has 3 components.

Clearly if a graph has a total of only one component, then the graph is called Connected, and on the other hand if the graph has more than one component then the graph is called Disconnected graph.

The following program finds the number of components in a graph. For representing a graph, I have used here the Adjacency Matrix representation of Graph.
Adjacency Matrix is a 2D array of size V x V where V is the number of vertices in a graph. If the adjacency matrix has an entry of 1 corresponding to the ith row and jth column, this means that there is an edge from the ith vertex to the jth vertex.
No, doubt we will need V x V bits in total to store the adjacency matrix of the graph, where V is the number of vertices. Note that many novice programmers will create an integer array of size V x V which will definitely lead to wastage of memory because every entry in the adjacency matrix is either 0 or 1, 0 representing no edge and 1 representing an edge. And because of this nature of the adjacency matrix we don't need to have an integer array when we can do the same task in a 2D bit array. This is what I have exactly done in the following program.

Now an obvious question will be that how to maintain a 2D bit array in a programming language like C. For this I have a 1D integer array, in which i will utilize each and every single bit to represent an edge between two vertices.

I will explain this using an example.
Suppose you have a graph of 5 vertices, the size of your adjacency list will be 25 bits. And we know that in a 32 bit C compiler (like gcc 4.8.2) these all 25 bits could be accommodated in a single integer, saving an enormous amount of memory.
But suppose you have 10 vertices, so then the size of your adjacency matrix will be 100 bits, which could be easily (and surely) accommodated in 4 integers, so the size of your adjacency matrix will be just 4 integers.

I think I have made myself clear, all the readers have got the concept and from now they will definitely appreciate concept of bit representation of the adjacency matrix.
The reader should note here that this representation is applicable only when the graph is un-weighted, that is there are no associated weights with the edges, otherwise this representation will not work.

Now I would like to explain the algorithm for finding the number of components in a graph given the adjacency matrix of the graph.
The basic idea of this algorithm is to merge adjacent vertices of the graph. We start with a vertex in the graph and merge all the adjacent vertices. Then we take the newly formed vertex after merging and again merge all the vertices that are adjacent to it. And we continue this step until no more merging is possible. After the exhaustive step when no more merging is possible, the number of remaining vertices will denote the number of components in the original graph.

Here I would like to add that, in adjacency matrix merging of ith vertex with the jth vertex can be accomplished by bit-wise OR operation, and I have followed the same in the source code presented below.

Here is the source code of all the things that I explained to you in above paragraphs:



one_D_bit_array.h

int get_one_D_bit_array(int ,int *);
void reset_one_D_bit_array(int ,int *);
void set_one_D_bit_array(int ,int *);


one_D_bit_array.c

#include"one_D_bit_array.h"
int get_one_D_bit_array(int i,int* arr)
{
 if((arr[i/32]&((unsigned int)1<<(31-i%32)))!=0)
  return 1;
 return 0;
}
void set_one_D_bit_array(int i,int *arr)
{
 arr[i/32]|=((unsigned int)1<<(31-i%32));  // to set its 31-(n%32) th bit.
}
void reset_one_D_bit_array(int i,int *arr)
{
 arr[i/32]&=(~((unsigned int)1<<(31-i%32))); // to reset its 31-(n%32) th bit.
}



two_D_bit_array.h

int get_two_D_bit_array(int ,int ,int *,int);
void set_two_D_bit_array(int ,int ,int *,int);
void reset_two_D_bit_array(int ,int ,int *,int);


two_D_bit_array.c

#include"two_D_bit_array.h"

/*  
  this function will return bit value in 
  ith row and 
  jth column
  from the array 'arr'
  which provides an abstraction of 2-D bit array of size n * n.
*/ 
int get_two_D_bit_array(int i,int j,int* arr,int n)
{
 int bitNumber=i*n+j;
 if((arr[bitNumber/32]&((unsigned int)1<<(31-bitNumber%32)))!=0)
  return 1;
 return 0;
}

/*  
  this function will set the bit value in 
  ith row and 
  jth column
  in the array 'arr'
  which provides an abstraction of 2-D bit array of size n * n
  to 1.
*/ 
void set_two_D_bit_array(int i,int j,int *arr,int n)
{ 
 int bitNumber=i*n+j;
 arr[bitNumber/32]|=((unsigned int)1<<(31-bitNumber%32));  // to set its 31-(bitNumber%32) th bit.
}

/*  
  this function will set the bit value in 
  ith row and 
  jth column
  in the array 'arr'
  which provides an abstraction of 2-D bit array of size n * n
  to 0.
*/ 
void reset_two_D_bit_array(int i,int j,int *arr,int n)
{
 int bitNumber=i*n+j;
 arr[bitNumber/32]&=(~((unsigned int)1<<(31-bitNumber%32))); // to reset its 31-(bitNumber%32) th bit.
}


graph.h

struct Graph
{
 int numberOfVertices,numberOfEdges;
 unsigned int*adjacencyMatrix;
};
struct Graph*makeNewGraph();
void initializeAdjacencyMatrix(struct Graph*);
void createEdge(struct Graph*,int,int);
void removeEdge(struct Graph*,int,int);
void showAdjacencyMatrix(struct Graph*);
int findNumberOfComponents(struct Graph*);


graph.c

#include<stdio.h>
#include<stdlib.h>
#include"Graph_AdjacencyMatrix.h"
#include"two_D_bit_array.h"
#include"one_D_bit_array.h"

struct Graph*makeNewGraph()
{
	struct Graph*g;
	g=(struct Graph*)malloc(sizeof(struct Graph));
	return g;
}
void initializeAdjacencyMatrix(struct Graph*g)
{
	/*
		The adjacencyMatrix corresponding to vertex u and v will contain 1 if there is an edge from u to v
		otherwise it will contain 0

		Description of data structure used for making adjacencyMatrix:
			* We will need n*n bits to represent the existence of an edge between two vertices
			* These n*n bits should be assumed to be arranged in the linear fashion
			* For implementing this linear fashion we will use an array of integers.
			* For a standard 32 bit compiler (like gcc 4.8.2) size of an integer is 32 bits (4 bytes).
			* By this linear arrangement of AdjacencyMatrix we will optimally exploit every single bit.
	*/
	int sizeOfIntegerColumns,i,j;
	sizeOfIntegerColumns=((g->numberOfVertices)*(g->numberOfVertices))/32+1;
	(g->adjacencyMatrix)=(unsigned int*)malloc(sizeof(unsigned int)*sizeOfIntegerColumns);
	for(i=0;i<sizeOfIntegerColumns;i++)
		(g->adjacencyMatrix)[i]=0;
}
void createEdge(struct Graph*g,int a,int b)
{
	set_two_D_bit_array(a,b,g->adjacencyMatrix,g->numberOfVertices);
}
void removeEdge(struct Graph*g,int a,int b)
{
	reset_two_D_bit_array(a,b,g->adjacencyMatrix,g->numberOfVertices);
}
void showAdjacencyMatrix(struct Graph*g)
{
	int i,j,bitNumber;
	printf("The adjacency Matrix of the Graph is as follows : \n");
	for(i=0;i<(g->numberOfVertices);i++)
	{
		for(j=0;j<(g->numberOfVertices);j++)
			printf("%d",get_two_D_bit_array(i,j,g->adjacencyMatrix,g->numberOfVertices));
		printf("\n");
	}
}
int findNumberOfComponents(struct Graph*g)
{
	/*
		first of all we need to create a copy of the AdjacencyMatrix.
	*/
	unsigned int *adjacencyMatrix_copy,*flag,sizeOfIntegerColumns,i,j,k,components;
	sizeOfIntegerColumns=((g->numberOfVertices)*(g->numberOfVertices))/32+1;
	adjacencyMatrix_copy=(unsigned int*)malloc(sizeof(unsigned int)*sizeOfIntegerColumns);
	for(i=0;i<sizeOfIntegerColumns;i++)
		adjacencyMatrix_copy[i]=(g->adjacencyMatrix)[i];
	/* copy of adjacencyMatrix created */

	/* 	now we need to keep the track of vertices being merged
		for this we need to introduce a one-D bit array that will keep track of this information.
		let this one-D bit array be flag.
	*/
	flag=(unsigned int *)malloc(sizeof(unsigned int)*(g->numberOfVertices)/32+1);
	for(i=0;i<(g->numberOfVertices)/32+1;i++)
		flag[i]=0;
	/*
		if the nth bit of flag array is 0 this means that the vertex with vertexNumber 'n' is still
		alive and is not merged with any other vertex.

		if the nth bit of flag array is 1 this means that the vertex with vertexNumber 'n' is dead
		and is merged with some other vertex and has no existence now.
	*/
	/* now we are ready for merging vertices in our dummy (copied) adjacencyMatrix.  */
	for(i=0;i<(g->numberOfVertices);i++)
	{
		if(get_one_D_bit_array(i,flag)==0) // means ith vertex is alive
		{
			for(j=0;j<(g->numberOfVertices);j++)
			{
				if(j!=i && get_one_D_bit_array(j,flag)==0) // means the jth vertex is alive
				{
					if(get_two_D_bit_array(i,j,adjacencyMatrix_copy,g->numberOfVertices)==1)
					{
						/*
							now we need to merge the ith node with the jth node
							for this we need to merge
								ith row with jth row, and
								ith col with jth col
						*/
						for(k=0;k<(g->numberOfVertices);k++) // merging the ith and jth rows
						{
							if(get_two_D_bit_array(i,k,adjacencyMatrix_copy,g->numberOfVertices) | get_two_D_bit_array(j,k,adjacencyMatrix_copy,g->numberOfVertices))
								set_two_D_bit_array(i,k,adjacencyMatrix_copy,g->numberOfVertices);
						}
						for(k=0;k<(g->numberOfVertices);k++) // merging the ith and jth cols
						{
							if(get_two_D_bit_array(k,i,adjacencyMatrix_copy,g->numberOfVertices) | get_two_D_bit_array(k,j,adjacencyMatrix_copy,g->numberOfVertices))
								set_two_D_bit_array(k,i,adjacencyMatrix_copy,g->numberOfVertices);
						}
						/* now the jth vertex is merged with ith vertex so the ith vertex should have no existence */
						/* so we need to set the jth bit of flag array to 1 */
						set_one_D_bit_array(j,flag); // declaring that the jth vertex is now dead.
					}
				}
			}
		}
	}
	/* 
		now the total number of components in the graph will be the number of vertices that still have zero 
		correponding to their vertex number in flag array.
	*/
	components=0;
	for(i=0;i<(g->numberOfVertices);i++)
		if(get_one_D_bit_array(i,flag)==0)
			components++;
	return components;
}


main.c

#include<stdio.h>
#include"graph.h"

int main()
{
 int i,n,a,b;
 struct Graph*g;
 g=makeNewGraph();
 printf("Enter the number of Vertices in the Graph : ");
 scanf("%d",&(g->numberOfVertices));
 printf("Enter the number of Edges in the Graph : ");
 scanf("%d",&(g->numberOfEdges));
 initializeAdjacencyMatrix(g);
 printf("NOTE : The ordering of the vertices is zero indexed.\n");
 for(i=0;i<(g->numberOfEdges);i++)
 {
  printf("Enter the edge Number %d : ",i+1);
  scanf("%d%d",&a,&b);
  createEdge(g,a,b);
 }
 showAdjacencyMatrix(g);
 printf("Number of components in the Graph = %d\n",findNumberOfComponents(g));
 printf("\nProgram execution successful...\n");
 return 0;
}


Makefile

all: hello
hello: one_D_bit_array.o two_D_bit_array.o graph.o main.o
 gcc one_D_bit_array.o two_D_bit_array.o graph.o main.o -o hello
one_D_bit_array.o: one_D_bit_array.c
 gcc -c one_D_bit_array.c
two_D_bit_array.o: two_D_bit_array.c
 gcc -c two_D_bit_array.c
main.o: main.c
 gcc -c main.c
graph.o: graph.c
 gcc -c graph.c


To find the source code on GitHub click here


Wednesday, 28 January 2015

Preprocessor Statements #ifdef, #else, #endif


Consider the following C program



#define FIRST
int main()
{
    int x, y, z;
#ifdef FIRST
    x=2; y=6; z=4;
#else
    printf("Enter x:");
    scanf("%d", &x);
    printf("Enter y:");
    scanf("%d", &y);
    printf("Enter z:");
    scanf("%d", &z);
#endif

    printf(“x:%d\ny:%d\nz:%d”);
    return 0;
}


Note that if FIRST is defined using the #define, the values of x, y and z are hardcoded to values of 2, 6 and 4. When FIRST is defined, all that is passed to the compiler is the code between the #ifdef and the #else. The code between the #else and the #endif is not seen by the compiler and is simply ignored. It is as if it were all a comment.
Once you have your routine working, and desire to insert the printf and scanfs, all that is required is to go back and delete the the #define FIRST. Now, the compiler now ignores the following statements:

a=2; b=6; c=4;
but does see the printf and scanfs.


Quite often you will have code which doesn't work, but you really don't want to throw it away. I see many students doing this;
/*
unwanted code
*/
And this is acceptable. Of course a problem arises is you have a comment in the unwanted code.
Thus, it is better to do this

#ifdef OLD
     unwanted code
#endif 


Wednesday, 14 January 2015

Disease and Diagnosis Example

THE TABLE GIVEN BELOW SHOWS THE HYPOTHETICAL TRAINING DATA FOR DISEASE DIAGNOSIS N=NO, Y=YES
Patient id#
Sore throat
Fever
Swollen Glands
congestion
Headache
Diagnosis
1
Y
Y
Y
Y
Y
Strep throat=1
2
N
N
N
Y
Y
Allergy=2
3
Y
Y
N
Y
N
Cold=3
4
Y
N
Y
N
N
Strep throat=1
5
N
Y
N
Y
N
Cold=3
6
N
N
N
Y
N
Allergy=2
7
N
N
Y
N
N
Strep throat=1
8
Y
N
N
Y
Y
Allergy=2
9
N
Y
N
Y
Y
Cold=3
10
Y
Y
N
N
Y
Cold=3

WRITE    A PROGRAM TO DISPLAY THE   DIAGNOSIS   WHEN USER ENTER THE SYMPTOMS OF A DISEASE BASED ON ABOVE GIVEN DATA.



#include<stdio.h>
#include<string.h>
int findDiagnosis(char**data,char *response,int *diagnosisNumber)
{
    int i,j,maxMatch=0,current_i,counter;
    for(i=0;i<10;i++)
    {
        counter=0;
        for(j=0;j<5;j++)
        {
            if(data[i][j]==response[j])
                counter++;
        }
        if(counter>maxMatch)
        {
            maxMatch=counter;
            current_i=i;
        }
    }
    return diagnosisNumber[current_i];
}

int main()
{
    int d;
    char data[10][5]={{'Y','Y','Y','Y','Y'},
    {'N','N','N','Y','Y'},
    {'Y','Y','N','Y','N'},
    {'Y','N','Y','N','N'},
    {'N','Y','N','Y','N'},
    {'N','N','N','Y','N'},
    {'N','N','Y','N','N'},
    {'Y','N','N','Y','Y'},
    {'N','Y','N','Y','Y'},
    {'Y','Y','N','N','Y'}};

    char diagnosis[3][20];
    char response[5];
    int diagnosisNumber[]={0,1,2,0,2,1,0,1,2,2};
    int i,j,maxMatch=0,current_i,counter;



    strcpy(diagnosis[0],"Strep Throat");
    strcpy(diagnosis[1],"Allergy");
    strcpy(diagnosis[2],"Cold");

    printf("Sore throat ? ");
    scanf(" %c",&response[0]);

    printf("Fever ? ");
    scanf(" %c",&response[1]);

    printf("Swollen Glands ? ");
    scanf(" %c",&response[2]);

    printf("congestion ? ");
    scanf(" %c",&response[3]);

    printf("Headache ? ");
    scanf(" %c",&response[4]);

    for(i=0;i<10;i++)
    {
        counter=0;
        for(j=0;j<5;j++)
        {
            if(data[i][j]==response[j])
                counter++;
        }
        if(counter>maxMatch)
        {
            maxMatch=counter;
            current_i=i;
        }
    }
    d=diagnosisNumber[current_i];

    printf("\n DIAGNOSIS : %s",diagnosis[d]);
    return 0;
}

Neural Network : Firing Rule


TABLE SHOWN BELOW DISPLAY THE    INPUT DATA   AND CORESSPONDING OUT DATA
APPLY THE FIRING RULE TO ABTAIN THE CORRECT TABLE USING. WE HAVE THE (0 TOUGHT SET) AND (1-TOUGHT SET)

X1:       0      0        0        0       1      1      1      1
X2:       0      0        1        1       0      0      1      1
X3:       0      1        0        1       0      1      0      1
OUT:      0      0       0/1      0/1     0/1     1     0/1     1

#include<stdio.h>
void print(int*arr,int n)
{
    int i;
    for(i=0;i<n;i++)
        printf("%d ",arr[i]);
    printf("\n\n");
}
int main()
{
    int i,j,counter,maxMatch,oneCount,zeroCount,current_j;
    int x1[]={0,0,0,0,1,1,1,1};
    int x2[]={0,0,1,1,0,0,1,1};
    int x3[]={0,1,0,1,0,1,0,1};

    int out[]={0,0,-1,-1,-1,1,-1,1};
    int newOut[8];

    for(i=0;i<8;i++)
        newOut[i]=out[i];
    for(i=0;i<8;i++)
    {
        counter=0;
        maxMatch=0;
        if(out[i]==-1)
        {
            for(j=0;j<8;j++)
            {
                counter=0;
                if(out[j]!=-1 && j!=i)
                {
                    if(x1[j]==x1[i])
                        counter++;
                    if(x2[j]==x2[i])
                        counter++;
                    if(x3[j]==x3[i])
                        counter++;
                }
                if(counter>maxMatch)
                    maxMatch=counter;
            }
            zeroCount=0;
            oneCount=0;
            for(j=0;j<8;j++)
            {
                counter=0;
                if(out[j]!=-1 && j!=i)
                {
                    if(x1[j]==x1[i])
                        counter++;
                    if(x2[j]==x2[i])
                        counter++;
                    if(x3[j]==x3[i])
                        counter++;

                    if(counter==maxMatch)
                    {
                        if(out[j]==0)
                            zeroCount++;
                        else if(out[j]==1)
                            oneCount++;
                    }
                }
            }
            if(zeroCount>oneCount)
                newOut[i]=0;
            else if(zeroCount<oneCount)
                newOut[i]=1;
            else
                newOut[i]=-1;
        }
    }
    printf("x1 : \n");
    print(x1,8);

    printf("x2 : \n");
    print(x2,8);

    printf("x3 : \n");
    print(x3,8);

    printf("old out : \n");
    print(out,8);

    printf("new out : \n");
    print(newOut,8);

    return 0;
}


Multi Point Cross Over using Bit Pattern

WRITE A PROGRAM TO DISPLAY MULTI POINT CROSSOVER USING BIT PATTERN AND ALSO USE THE GRAPHICAL REPRESENTATIONS

#include<stdio.h>

void printBitRepresentation(unsigned int parent, unsigned int crossOverPoint1,unsigned int crossOverPoint2)
{
    unsigned int num,i;
    num=1<<31;
    for(i=0;i<32;num>>=1,i++)
    {
        if(parent & num)
            printf("1");
        else
            printf("0");

        if(i==crossOverPoint1-1)
            printf(" | ");

        if(i==crossOverPoint2-1)
            printf(" | ");
    }
    printf("\n");
}
void printChildren(unsigned int parent1,unsigned int parent2,unsigned int crossOverPoint1,unsigned int crossOverPoint2)
{
    unsigned int num,i,a=0,b=0,c=0,d=0,e=0,f=0,child1,child2;
    num=1<<31;
    for(i=0;i<crossOverPoint1;num>>=1,i++)
    {
        if(parent1 & num)
            a+=num;
        if(parent2 & num)
            d+=num;
    }
    for(i=crossOverPoint1;i<crossOverPoint2;num>>=1,i++)
    {
        if(parent1 & num)
            b+=num;
        if(parent2 & num)
            e+=num;
    }
    for(i=crossOverPoint2;i<32;num>>=1,i++)
    {
        if(parent1 & num)
            c+=num;
        if(parent2 & num)
            f+=num;
    }
    child1=a+e+c;
    child2=d+b+f;
    printf("\n\nChild 1 = %u\n",child1);
    printf("Child 2 = %u\n",child2);

    printBitRepresentation(child1,crossOverPoint1,crossOverPoint2);
    printBitRepresentation(child2,crossOverPoint1,crossOverPoint2);

}
int main()
{
    unsigned int parent1,parent2,crossOverPoint1,crossOverPoint2;
    printf("Enter parent number 1 :");
    scanf("%d",&parent1);
    printf("Enter parent number 2 :");
    scanf("%d",&parent2);

    printf("Enter the Cross-Over point 1 [between 0 to 32]: \n");
    scanf("%d",&crossOverPoint1);
    printf("Enter the Cross-Over point 2 [between 0 to 32]: \n");
    scanf("%d",&crossOverPoint2);


    printf("\n\nBit representation for Parents is : \n");
    printBitRepresentation(parent1,crossOverPoint1,crossOverPoint2);
    printBitRepresentation(parent2,crossOverPoint1,crossOverPoint2);

    printChildren(parent1,parent2,crossOverPoint1,crossOverPoint2);
    return 0;
}


Single Point Cross Over using Bit Pattern

WRITE A PROGRAM TO DISPLAY SINGLE POINT CROSSOVER USING BIT PATTERN AND ALSO USE THE GRAPHICAL REPRESENTATIONS


/*
    WRITE A PROGRAM TO DISPLAY SINGLE POINT CROSSOVER USING BIT PATTERN AND ALSO USE THE GRAPHICAL REPRENTATIONS
*/

#include<stdio.h>

void printBitRepresentation(unsigned int parent, unsigned int crossOverPoint)
{
    unsigned int num,i;
    num=1<<31;
    for(i=0;i<32;num>>=1,i++)
    {
        if(parent & num)
            printf("1");
        else
            printf("0");

        if(i==crossOverPoint-1)
            printf(" | ");
    }
    printf("\n");
}
void printChildren(unsigned int parent1,unsigned int parent2,unsigned int crossOverPoint)
{
    unsigned int num,i,a=0,b=0,c=0,d=0,child1,child2,j;
    num=1<<31;
    for(i=0;i<crossOverPoint;num>>=1,i++)
    {
        if(parent1 & num)
            a+=num;
        if(parent2 & num)
            c+=num;
        if(i==crossOverPoint-1)
        {
            num>>=1;
            for(j=crossOverPoint;j<32;num>>=1,j++)
            {
                if(parent1 & num)
                    b+=num;
                if(parent2 & num)
                    d+=num;
            }
        }
    }

    child1=a+d;
    child2=c+b;
    printf("\n\nChild 1 = %u\n",child1);
    printf("Child 2 = %u\n",child2);

    printBitRepresentation(child1,crossOverPoint);
    printBitRepresentation(child2,crossOverPoint);
}
int main()
{
    unsigned int parent1,parent2,crossOverPoint;
    printf("Enter parent number 1 :");
    scanf("%u",&parent1);
    printf("Enter parent number 2 :");
    scanf("%u",&parent2);

    printf("Enter the Cross-Over point for single Point cross over [between 0 to 32]: \n");
    scanf("%d",&crossOverPoint);

    printf("\n\nBit representation for Parents is : \n");
    printBitRepresentation(parent1,crossOverPoint);
    printBitRepresentation(parent2,crossOverPoint);

    printChildren(parent1,parent2,crossOverPoint);
    return 0;
}


Saturday, 10 January 2015

Expression Evaluation using Stacks (PostFix Technique) in C (Makefile)

header.h

long long int solveExpression(char *);
struct Node
{
 int data;
 char op;
 struct Node*next;
};
struct LinkedList
{
 struct Node*start; 
};
struct StackNode
{
 char op;
 struct StackNode*next;
};
struct Node*makeNode(int data,char op);
struct Node*insertAtEnd(struct Node*start, struct Node*newNode);
struct Node*deleteNode(struct Node*start,int data,char op);
void printList(struct Node*start);
struct StackNode*makeStackNode(char op);
struct StackNode*push(struct StackNode*top, struct StackNode*newNode);
struct StackNode*pop(struct StackNode**top);


LinkedList.c

#include"header.h"
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
struct Node*makeNode(int data,char op)
{
 struct Node*newNode;
 newNode=(struct Node*)malloc(sizeof(struct Node*));
 newNode->data=data;
 newNode->op=op;
 newNode->next=NULL;
 return newNode;
}

struct Node*insertAtEnd(struct Node*start, struct Node*newNode)
{
 struct Node*currentNode;
 if(!start)
  return newNode;
 for(currentNode=start;currentNode->next;currentNode=currentNode->next);
 currentNode->next=newNode;
 return start;
}

struct Node*deleteNode(struct Node*start,int data,char op)
{
 struct Node*currentNode,*prevNode=NULL,*temp,*prev;
 for(prevNode=NULL,currentNode=start;;prevNode=currentNode,currentNode=currentNode->next)
 {
  if(currentNode->data==data && currentNode->op==op)
   break;
 }
 if(currentNode==start)
 {
  temp=start;
  start=start->next;
  free(temp);
 }
 else
 {
  prev->next=currentNode->next;
  free(currentNode);
 }
 return start;
}

void printList(struct Node*start)
{
 while(start)
 {
  if((start->op)!='\0')
   printf("%c\n",start->op);
  else
   printf("%d\n",start->data);
  start=start->next;
 }
 printf("\n");
}



LinkedListStack.c

#include"header.h"
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
struct StackNode*makeStackNode(char op)
{
 struct StackNode*newNode;
 newNode=(struct StackNode*)malloc(sizeof(struct StackNode*));
 newNode->op=op;
 newNode->next=NULL;
 return newNode;
}

struct StackNode*push(struct StackNode*top, struct StackNode*newNode)
{
 if(!top)
  return newNode;
 newNode->next=top;
 return newNode;
}

struct StackNode*pop(struct StackNode**top)
{
 struct StackNode*returnNode;
 if(!(*top))
  return NULL;
 returnNode=(*top);
 *top=(*top)->next;
 return returnNode;
}



main.c

#include<string.h>
#include<stdio.h>
#include"header.h"

int main()
{
 char str[100000];
 printf("Enter the expression : ");
 scanf("%[^\n]s",str);
 
 printf("\nAnswer = %lld\n\n",solveExpression(str));
 return 0;
}



solveExpression.c

#include<stdio.h>
#include<stdlib.h>
#include"header.h"
int getPriority(char c)
{
 if(c=='(')
  return -1;
 if(c=='+' || c=='-')
  return 0;
 if(c=='*' || c=='/' || c=='%')
  return 1;
 if(c=='^')
  return 2;
}

struct LinkedList convertToPostfix(struct LinkedList infix)
{
 struct Node*infixNode;
 struct StackNode*top,*temp;
 struct LinkedList postfix;
 top=NULL;
 postfix.start=NULL;
 for(infixNode=infix.start;infixNode;infixNode=infixNode->next)
 {
  if(infixNode->op=='(')
  {
   top=push(top,makeStackNode(infixNode->op));
   continue;
  }
  if(infixNode->op==')')
  {
   while(top && top->op!='(')
   {
    temp=pop(&top);
    postfix.start=insertAtEnd(postfix.start,makeNode(-2147483647,temp->op));
   }
   pop(&top);
   continue; 
  }
  if(infixNode->op=='\0')
  {
   postfix.start=insertAtEnd(postfix.start,makeNode(infixNode->data,infixNode->op));
  }
  else
  {
   if(top==NULL)
    top=push(top,makeStackNode(infixNode->op));
   else
   {
    if(getPriority(infixNode->op)>getPriority(top->op))
    {
     top=push(top,makeStackNode(infixNode->op));
    }
    else
    {
     while(top && getPriority(infixNode->op) <= getPriority(top->op))
     {
      temp=pop(&top);
      postfix.start=insertAtEnd(postfix.start,makeNode(-2147483647,temp->op));
     }
     top=push(top,makeStackNode(infixNode->op));
    }
    
   }
  }
 }
 while(top)
 {
  temp=pop(&top);
  postfix.start=insertAtEnd(postfix.start,makeNode(-2147483647,temp->op));
 }
 return postfix;
}
int operate(int a,int b,char c)
{
 switch(c)
 {
  case '+':
   return a+b;
  case '-':
   return a-b;
  case '*':
   return a*b;
  case '/':
   return a/b;
  case '%':
   return a%b;
  case '^':
   return (a^b);
 }
 return 0;
}
long long int evaluate(struct LinkedList postfix)
{
 int answer;
 struct Node*ptr,*prev1,*prev2;
 while((postfix.start)->next)
 {
  for(ptr=postfix.start,prev1=NULL,prev2=NULL;ptr && ptr->op=='\0';prev1=prev2,prev2=ptr,ptr=ptr->next);
  answer=operate(prev1->data,prev2->data,ptr->op);
  prev1->data=answer;
  
  prev1->next=ptr->next;
  free(prev2);
  free(ptr);
 }
 return (postfix.start)->data;
}
long long int solveExpression(char str[])
{
 struct LinkedList infix,postfix;
 int i,num;
 infix.start=NULL;
 for(i=0;str[i];)
 {
  if(str[i]==' ')
  {
   i++;
   continue;
  }if(str[i]<='9' && str[i]>='0')
  {
   for(num=0;str[i] && str[i]<='9' && str[i]>='0';i++)
    num=num*10+str[i]-'0';
   infix.start=insertAtEnd(infix.start,makeNode(num,'\0'));
  }
  else
  {
   infix.start=insertAtEnd(infix.start,makeNode(-2147483647,str[i]));
   i++;
  }
 }
 postfix=convertToPostfix(infix);
 return evaluate(postfix);
}


Makefile

all: hello
hello: main.o solveExpression.o LinkedList.o LinkedListStack.o
 gcc main.o solveExpression.o LinkedList.o LinkedListStack.o -o hello
main.o: main.c
 gcc -c main.c
evaluateExpression.o: solveExpression.c
 gcc -c solveExpression.c
LinkedList.o: LinkedList.c
 gcc -c LinkedList.c
LinkedListStack.o: LinkedListStack.c
 gcc -c LinkedListStack.c