Tuesday, December 8, 2015

Read very large strings of UNKNOWN length

char buffer[10];
    char *s = 0;
    size_t cur_len = 0;
    while (fgets(buffer, sizeof(buffer), stdin) != 0)
    {
        size_t buf_len = strlen(buffer);
        char *extra = realloc(s, buf_len + cur_len + 1);
        if (extra == 0)
            break;
        s = extra;
        strcpy(s + cur_len, buffer);
        cur_len += buf_len;
    }

Friday, November 6, 2015

Graph implementation using adjacency list

#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
    int key;
    struct node * next;
}node;
typedef struct list
{
    struct node * head;
}list;
typedef struct GRAPH
{
    int V;
    struct list * array;
}GRAPH;
node * newnode(int k)
{
    node *n=(node *)malloc(1*sizeof(node));
    n->key=k;
    return n;
}
GRAPH *newgraph(GRAPH * g,int v)
{   g=(GRAPH *)malloc(sizeof(GRAPH));
    g->V=v;int i;
    g->array=(list *)malloc(v*sizeof(g->array));
    for(i=0;i<v;i++)
         g->array[i].head=NULL;
    return g;
}
void add_edge(GRAPH * g,int s , int t)
{
    node *n=newnode(t);
    n->next=g->array[s].head;
    g->array[s].head=n;
    node *n2=newnode(s);
    n2->next=g->array[t].head;
    g->array[t].head=n2;
}

void delete_edge(GRAPH * g,int s , int t)
{
     if(g->array[s].head==NULL){printf("There is no edge between %d and %d \n", s , t);return;}
    node * ptr1=g->array[s].head;
    if(ptr1->next==NULL)
        {if(ptr1->key==t){free(ptr1);ptr1=NULL;}return;}
    if(ptr1->key==t)
    {  g->array[s].head=ptr1->next;free(ptr1);return;}

    node * ptr2=g->array[s].head->next;

    while(ptr2!=NULL)
    {
        if(ptr2->key!=t)
          {
            ptr1=ptr2;
            ptr2=ptr2->next;
           }
          else break;

    }
   if(ptr2!=NULL)
    {
      if(ptr2->key==t)
        {ptr1->next=ptr2->next;
        free(ptr2);
        }
      else printf("There is no edge between %d and %d \n", s , t);
    }
    else
         printf("There is no edge between %d and %d \n", s , t);

}
void printgraph(GRAPH *g)
{
    int v,i;
    v=g->V;
    for(i=0;i<v;i++)
        {   node * ptr=g->array[i].head;            printf("%d->",i);

            while(ptr!=NULL)
            {
                printf("%d->",ptr->key);
                ptr=ptr->next;
            }
            printf("\n");
        }
}
void remove_edge(GRAPH *graph ,int a , int b)
{   printf("deleting edge %d-%d \n",a,b);
    delete_edge(graph,a,b);delete_edge(graph,b,a);

}
int main()
{   int size=5;
    GRAPH *graph=newgraph(graph,size);
    add_edge(graph,0,1);add_edge(graph,0,2);add_edge(graph,0,4);
    add_edge(graph,1,4);add_edge(graph,1,2);add_edge(graph,1,3);
    add_edge(graph,2,3);add_edge(graph,2,4);
    add_edge(graph,3,4);
    printgraph(graph);
    remove_edge(graph,2,3);
    remove_edge(graph,1,4);
    remove_edge(graph,1,3);


           printgraph(graph);
    printf("success\n");
return 0;
}



Tuesday, October 13, 2015

program to find the linearly dependent columns in multidimensional array

#include<stdio.h>
#include<stdlib.h>
int main()
{

int i,j,k,m,n,len,col,a[9][9]={{2,3,6,5,1,2,3,6,9},{2,3,6,5,4,2,3,6,2},{2,3,6,5,4,2,3,1,9},{2,3,6,5,4,2,3,6,9},{2,3,6,5,4,2,3,6,9},
       {2,3,6,5,4,2,3,6,9},{2,3,6,5,4,3,3,6,9},{2,3,6,5,4,2,4,6,9},{2,3,6,5,8,2,3,6,9}
        };

for(i=0;i<8;i++)
    for(j=i+1;j<9;j++)
{ printf("here");
     if(a[0][i]%a[0][j]==0)
     {  printf("here1");
           len=1;
         col=i;
         for(k=1;k<9;k++)
         {
             if(a[k][i]%a[k][j]!=0)
                 len=0;
         }
       printf("here2");
     }
     else if(a[0][j]%a[0][i]==0)
     {   len=1;printf("here3");
         col=j;
         for(k=1;k<9;k++)
         {   len=1;printf("in55");
             if(a[k][j]%a[k][i]!=0)
                 len=0;
                 printf("in56");
         }
         printf("here4");
     }
     if(len==1)printf("\ncolumn : %d is linearly dependent",col);
}
return 0;
}

Saturday, October 10, 2015

Implementation of longest common sub-sequence in c

#include<stdio.h>
#include<stdlib.h>
int max(int a,int b){return (a>b)?a:b;}
char *x, *y;
int lcs(int i,int j)
 {
  if(i==0||j==0)return 0;
  else if(i>0&&j>0&&x[i]==y[j]) return lcs(i-1,j-1)+1;
  else if(i>0&&j>0&&x[i]!=y[j]) return max(lcs(i-1,j),lcs(i,j-1));
}
int main()
{int n=10,m=5;

 x=(char *)malloc(n*sizeof(char ));
 y=(char *)malloc(m*sizeof(char ));
 gets(x);
 gets(y);
 //sizeof longest common subsequence among first n letters of x and first m letters of y
 printf("%d",lcs(n,m));
return 0;
}

Thursday, October 8, 2015

Represent graph with adjacency list : C program

#include <stdio.h>
#include <stdlib.h>
typedef struct node{int key;struct node * next;}node;
node * init_node(node * n,int b){n=(node *)malloc(sizeof(node));n->key=b;n->next=NULL;return n;}
node **list,*front=NULL,*rear=NULL;
void enqueue(node * n)
{ if(rear==NULL)front=rear=n;
  else{ rear->next=n;rear=n; } }

void add_edge(int a,int b)
{  node * ptr=NULL,*n=NULL;
   n=init_node(n,b);
    if(list[a]->next==NULL){list[a]->next=n;}
  else{  ptr=list[a]; while(ptr->next!=NULL)ptr=ptr->next;ptr->next=n;}
}
int main()
{int n=4,i,j;node * ptr=NULL;
 list=(node **)malloc(n*(sizeof(node *)));

for(i=0;i<n;i++)
{  list[i]=(node *)malloc(n*(sizeof(node *)));list[i]->next=NULL;list[i]->key=i;}

add_edge(0,3);add_edge(0,1);add_edge(1,3);
add_edge(2,0);add_edge(3,2);add_edge(2,1);
for(j=0;j<n;j++)
    if(list[j]->next!=NULL)
         { printf("[ %d ]",j);ptr=list[j]->next;
           while(ptr!=NULL){printf("--> %d ",ptr->key);ptr=ptr->next;}
          printf("\n");
         }

printf("IN THE END......");
return 0;
}

Saturday, October 3, 2015

Program for String Matching with Finite Automata in C

#include <stdio.h>
#include <stdlib.h>
char * prefix(char * c,int start, int end,int size)
{   int i;
    char *temp=(char *)malloc(size*sizeof(char));
    for(i=0;i<size;i++)
       temp[i]=c[start++];
    return temp;
}
char * suffix(char * c,int start, int end,int size)
{   int i,j;
    char *temp=(char *)malloc(size*sizeof(char));
    for(j=0,i=end-size+1;i<=end;i++,j++)
       temp[j]=c[i];
    return temp;
}
int match(char * a, char *b)
{  int i=0;
    while(a[i]!='\0')
     {
if(a[i]!=b[i])
 return 0;
i++;
     }
    return 1;
}
int sigma(char * t , char * p ,int i)
{
  int j,v=0;
  for(j=0;p[j]!='\0';j++)
     if(match(suffix(t,0,i,j+1),prefix(p,0,j,j+1)))
v=j+1;
  return v;
}
int main()
{  char a[]="dfhghjgfjschhscgchgfbgfsgfjh";
   char b[]="jhgfj";
   printf("%d\n",sigma(a,b,8));
   
 
}

Friday, October 2, 2015

Implmentation of Rabin-Karp Algorithm in c

#include <stdio.h>
#include<stdlib.h>
int hash (char * a,int s,int t)
{ int h=0;
    for(;s<=t;s++)
        h+=a[s];
       return h;
}
int match(char * a,int a1,int a2,char * b, int b1,int b2)
{  
    for(;a1<=a2,b1<=b2;a1++,b1++)
       { if(a[a1]!=b[b1])
           return 0;
       }
       return 1;
}   
   

void rk(char*a,char *b,int as,int bs)

   int ph=hash(b,0,bs-1),i;
   for(i=0;i<(as-bs+1);i++)
    { if(hash(a,i,i+bs-1)==ph)
        if(match(a,i,i+bs-1,b,0,bs-1))
      { printf("  match for < %s > found at position : %d ",b,i+1);}
    }
        
    
}
void main()
{  
 char t[]="abcdefghijklmnopqrstuvwxyz";
 char p[]="klmnop";
    int st=sizeof(t)-1;
    int  sp=sizeof(p)-1;
    rk(t,p,st,sp);
    
    
}

Tuesday, September 29, 2015

Simple string matching algorithm to find position of a pattern in a given string without using any string function in C

#include<stdio.h>
#include<stdlib.h>
void main()
{ int i=0,j,count;
  char string[]={"kfhisdcodesoecodeupzz"};
  char pattern[]={"code"};
 
 
  for(i=0;i<sizeof(string)-1;i++)
     {
     
       if(string[i]==pattern[0])
         { count =1;

           for(j=1;j<sizeof(pattern)-1;j++)
              {
                if(pattern[j]==string[i+j])
                   count++;
                else break;
              }

         if(count==(sizeof(pattern)-1))
         printf("\none match at position : %d ",i);
           
         }
     
     }
printf("\n");
}

Saturday, September 26, 2015

Implementation of Breadth First search in C using dynamic adjacency list

#include <stdio.h>
#include <stdlib.h>
typedef struct node{int key;struct node * next;}node;
node * init_node(node * n,int b){n=(node *)malloc(sizeof(node));n->key=b;n->next=NULL;return n;}
node **list,*front=NULL,*rear=NULL;
void enqueue(node * n)
{ if(rear==NULL)front=rear=n;
  else{ rear->next=n;rear=n; } }
node * dequeue()
{
if(front==NULL&&rear==NULL){return NULL;}
if(front==rear){ node *temp=front;front=rear=NULL;return temp;}
node * temp=front;front=front->next;return temp;
}
void add_edge(int a,int b)
{  node * ptr=NULL,*n=NULL,*p;
   n=init_node(n,b);
    if(list[a]==NULL){p=init_node(p,a);list[a]=p;}
    ptr=list[a]; while(ptr->next!=NULL)ptr=ptr->next;ptr->next=n;

    ptr=NULL;n=NULL;
   n=init_node(n,a);
    if(list[b]==NULL){p=init_node(p,b);list[b]=p;}
    ptr=list[b]; while(ptr->next!=NULL)ptr=ptr->next;ptr->next=n;
}
void dfs(int s,int n)
{   node * ptr;int visited[n],i,d=6,parent[n],distance[n],parenti;
      for(i=0;i<n;i++){visited[i]=0;parent[i]=0;distance[i]=-1;}
    if(list[s]==NULL)return;
  enqueue(list[s]);
  parenti=s;
  distance[s]=0;
  visited[s]=1;
printf("\nDFS Distance from %d  :\n",s);
  while(front!=NULL)
  {
     ptr=dequeue();
     parenti=ptr->key;
     ptr=list[ptr->key]->next;

    while(ptr!=NULL)
     {   if(!visited[ptr->key])
         {enqueue(ptr);if(parent[ptr->key]==0)parent[ptr->key]=parenti;visited[ptr->key]=1;
          distance[ptr->key] =distance[parent[ptr->key]]+6;
          printf(" node-%d:parent-:%d:distance:%d\n ",ptr->key,parent[ptr->key],distance[ptr->key]);}
         ptr=ptr->next;
     }


  }
}
int main()
{int n=10,i,j;node *ptr=NULL;
 list=(node **)malloc(n*(sizeof(node *)));

for(i=0;i<n;i++)
{  list[i]=(node *)malloc(n*(sizeof(node *)));list[i]=NULL;}

add_edge(2,1);
add_edge(0,1);add_edge(2,0);
add_edge(2,3);
add_edge(9,6);add_edge(9,0);add_edge(9,5);add_edge(9,4);add_edge(9,7);add_edge(9,8);add_edge(9,3);
add_edge(8,7);add_edge(8,6);
add_edge(7,2);add_edge(7,2);
add_edge(6,0);add_edge(6,1);
add_edge(5,4);add_edge(5,2);add_edge(5,3);
add_edge(4,2);
add_edge(3,0);add_edge(3,1);
add_edge(1,0);

for(j=0;j<n;j++)
    if(list[j]!=NULL)
         { ptr=list[j];
           while(ptr!=NULL){printf("%d --> ",ptr->key);ptr=ptr->next;}
          printf("\n");
         }
dfs(3,10);

return 0;
}

Implementation of Binary Search Tree in C using dynamic linked list

//Binary Search Tree
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
  int key;
  struct node *left;
  struct node* right;
}node;

void printIO(node * n)
{ if(!n)return;
  if(n->left)
    printIO(n->left);
  printf("%d.",n->key);
  if(n->right)
    printIO(n->right);
}

node * create(node * n,int k)
{ n=(node *)malloc(sizeof(node));
  n->key=k;
  n->left=NULL;
  n->right=NULL;  
 return n;
 }

node * insert(node * n,int k)
{  
   node * root=n;
   if(n==NULL)
     {n= create(n,k);printf("%d.",k);}
   else if(k>n->key){n->right= insert(n->right,k);}
   else if(k<=n->key){n->left= insert(n->left,k);} 
   return n;
}

int main()
{
node * root=NULL;
printf("\n Inserting Sequence\n");
root=insert(root,202);root=insert(root,125);root=insert(root,255);root=insert(root,313);
root=insert(root,116);root=insert(root,222);root=insert(root,150);

printf("\n In Order of Created Binary Search tree\n");
printIO(root);
printf("\n");
return 0;
}

Friday, September 25, 2015

Implementation of AVL tree in C

#include<stdio.h>
#include<stdlib.h>
int kk;
typedef struct node{
int key;
int height;
struct node * left;
struct node * right;
}node;

node * create(node * n,int k)
{ n=(node *)malloc(sizeof(node));
  kk=k;
  n->key=k;
  n->height=1;
  n->left=NULL;
  n->right=NULL;
  return n;
}

int max(int a,int b){return (a<b)?b:a;}

node *updateheight(node *n )
{
  if(n->left!=NULL&&n->right!=NULL)
  {n->height=max(n->left->height,n->right->height)+1;printf("height updated\n");}
  else if(n->left!=NULL)
  {n->height=n->left->height;printf("height updated\n");}
  else if(n->right!=NULL)
  {n->height=n->right->height;printf("height updated\n");}
  else
  n->height=1;

  return n;
}
node * rotateR(node * r)
{
 
  node *n=r->left;
  node *temp;
  if(r->left->right!=NULL)
    temp=r->left->right;
  else temp=NULL;
  n->right=r;
  r->left=temp;
  if(n->right!=NULL)
  n->right=updateheight(n->right);
  n=updateheight(n);
  printf(".R.");
 return n;
 
}
node * rotateL(node * r)
{ node *n=r->right;
  node *temp;
  if(r->right->left!=NULL)
  temp=r->right->left;
  else temp =NULL;
  n->left=r;
  r->right=temp;
  updateheight(n->left);
  updateheight(n);
  printf(".L.");
  return n;

}

node * balance(node *n,int k)
{ int balance,l=0,r=0;
   if(n->left)
     l=n->left->height;
   if(n->right)
     r=n->right->height;
   balance=l-r;
     if(balance>1&&k<=n->left->key)
        {n=rotateR(n);printf("LL..");}
     else if(balance>1&&k>n->left->key)
       {printf("LR..");n=rotateL(n);n=rotateR(n);}
     else if(balance<-1&&k>n->right->key)
       {n=rotateL(n);printf("RR..");}
     else if(balance<-1&&k<=n->left->key)
       {n=rotateR(n);n=rotateL(n);printf("RL..");}

  return n;

}

node * insert(node * r,int k)
{
   if(r==NULL){node *n=create(n,k);r=n;}
   else if(k<=r->key){r->left=insert(r->left,k);r->height=r->left->height+1;r=balance(r,kk);}
   else if(k>r->key){r->right=insert(r->right,k);r->height=r->right->height+1;r=balance(r,kk);}
   return r;
}
void printAVLIO(node *r)
{
    if(!r)return;
    if(r->left)printAVLIO(r->left);
    printf("\n%d..",r->key);
    printf(".height.%d..\n",r->height);
    if(r->right)printAVLIO(r->right);
}

int main()
{
  node *root=NULL;
  int i,a[]={50,25,75,70,60},k=sizeof(a)/sizeof(int);
  printf("Inseting sequence into the AVL tree\n");
  for(i=0;i<k;i++)
     printf("%d..",a[i]);printf("\n");
  i=0;
  while(i<k)
     {root=insert(root,a[i]);i++;}
  printAVLIO(root);
return 0;
}

Sunday, September 6, 2015

Program to Build binary MaxHeap using ANSI C

#include<stdio.h>
#include<stdlib.h>
#include<limits.h>

int c,i,j;

int left(int j){return j*2+1;}
int right(int j){return j*2+2;}
int parent(int j) {return (j-1)/2;}

typedef struct node
{  int data;}node;

typedef struct heap
{  int capacity;
  int heapSize;
  node *element;
}heap;

void swap(node *x,node *y)
{ node *temp; temp=x; y=x; x=temp; }

initHeap(heap *h,int cap){h->capacity=cap;}

printHeap(heap *h){
for (i=0;i<h->capacity;i++)
    printf("\n %d",h->element[i].data);
}


insertKey(heap *h,int k)
{
   if(!(h->capacity))
     h->element=malloc(sizeof(node));
  else
     h->element=realloc(h->element,(h->capacity+1)*sizeof(node));
  node n;
  n.data=k;
  int i=(h->heapSize)++;
  while(i&&h->element[i].data>h->element[parent(i)].data)
       h->element[i]=h->element[parent(i)];
  h->element[i]=n;
}

void heapify(heap *h,int i)
{
   int max=i;
   if(h->element[left(i)].data>h->element[i].data)
     max=left(i);
  if(h->element[right(i)].data>h->element[i].data)
     max=right(i);
  if(i!=max)
    swap(&(h->element[max]),&(h->element[i]));
  heapify(h,max);
}

int extractMax(heap *h)
{
  int max=h->element[0].data;
   h->element[0]=h->element[(h->heapSize)--];
   h->element=realloc(h->element,h->heapSize*sizeof(node));
 
  return max;

}

deleteKey(heap *h,int k)
   {  if(h->heapSize)
      {  h->element[k].data=INT_MAX;
         heapify(h,k);
         int d=extractMax(h);
      }
      else printf("\n MaxHeap Is Empty");

   }

void main()
{
 int capacity=0;
 heap maxHeap;
 initHeap(&maxHeap,capacity);
char c='c';
int key;
  while (c=='c')
 { printf("\ni...insert");
  printf("\np...print");
  printf("\nm...get max");
  printf("\ne...exit");
  printf("\n\n........ENTER CHOICE::");
  c=getchar();
  switch (c)
        {
          case 'i' :
          printf("\nEnter the number to be inserted : ");
          scanf("%d",&key);
          insertKey(&maxHeap,key);
          printf("\n");
          printHeap(&maxHeap);
          break;
          case 'p':
          printf("\n");
          printHeap(&maxHeap);
          break;
          case 'm':
          printf("%d",extractMax(&maxHeap));
          default : break;
        }

 printf("\nPress....c...To Continue");
 printf("\nPress....any other key...EXIT");
 c=getchar();
printf("\n");
}
 

}

Monday, August 24, 2015

Program for Gauss-Jordan Elimination without frills

#include <iostream>
#include <cmath>
using namespace std;
                
int main ()
{

        int a,z,i,j;
        cout << "Enter the number of equations \n";
        cin >> a;
        float ar [a][a+1];
        
        cout << "Entering the elements of the array \n";
        for (i=0;i<a;i++)
        {        
        for (j=0; j<(a); j++)
        {
        if (i==j)
        {
         ar[i][j] = 2;
        }
        else if(i!=j)
        {
        ar[i][j] = -1;
        }
        }
        }

        for (i=0;i<a;i++)
        {
        ar[i][a] = -97;
        }

        

        
        cout << " \n\n GAUSS JORDAN ELIMINATION \n";
        float temp,max;        
        int k,l;
        
        for (i=0;i <a; i++)
        {
        max = ar[i][i]; 
        k=i;
        for (j=i;j <a; j++)
        {
        
        
        if (abs(ar[j][i]) > abs(max))        
        {
        
        
        max = ar[j][i];
        
        k=j;
        
        }
        }
        
        for (l=0;l<a+1;l++)
        {
        
        temp = ar[i][l];
        ar[i][l] = ar[k][l];
        ar[k][l] = temp;
        
        }
        
        
        

        
        int x,y;
        float z, rat;
        z = ar[i][i]; 
        
        if (z != 0)
        {
        for (x=i+1; x <a; x++)
        {
        
        rat = (ar[x][i]) / (ar[i][i]);        
        
        for (y=0;y<a+1;y++)
        {
        ar[x][y] = ar[x][y] - (rat*ar[i][y]);
        }
        }
        }

        
        }
        
        int ab;
        float x[a];
        for (ab=(a-1);ab>-1;ab--)
        {
         x[ab]=ar[ab][a];
        
        for (i=ab+1;i<a;i++)
        {
        x[ab]=x[ab]-(ar[ab][i]*x[i]);
        }
        x[ab] = (x[ab]/ar[ab][ab]);
        
        }
        

        for (i=0;i<a;i++)
        {
        cout << "x["<<i<<"] \t= " << x[i] <<endl;
        }
        
return 0;
        }

python code to change extension of all files in a folder

import os

for root,dirs,files in os.walk('./'):
   for file in files:
       if file.endswith('.oldext'):
          F=open(os.path.join(root,file),'r')
          W=open('./foldername/'+file.replace('.oldext','.newext'),'w')
          for line in F.readlines():
             W.write(line)
           W.close()
           F.close()
print 'All Extensions changed Successfully'

----------------------------------------------------------
change the file extensions as your need 
replace oldext with the extension your files are currently having
replace newext with the new extension you want to have for all of ur files

save the above code in a file with .py extension
create a folder named foldername in same directory where the python file is saved 

keep all the files whose extension you want to change in the same folder as code   file