Sunday, September 7, 2014

Implement a stack using one queue

Implement stack only using one queue.



 #include<stdio.h>  
 #include<stdlib.h>  
 typedef struct queue node;  
 struct queue{  
         int d;  
         node *n;          
   
 };  
 int size=0;  
 node *f,*r;  
 void enq(int d)  
 {  
         node *t;  
         t=(node *)malloc(sizeof(node));  
         t->d=d;  
         t->n=NULL;  
         if(r)  
         {  
                 r->n=t;  
                 r=t;  
         }  
         else  
         {  
                 f=r=t;  
         }  
         size++;  
 }  
 node *deq()  
 {  
         node *t;  
         if(f)  
         {  
                 size--;  
                 t=f;  
                 f=f->n;  
                 return t;  
   
         }  
         else  
         {  
                 printf("Error");  
         }  
 }  
 void push(int d)  
 {  
         enq(d);  
   
 }  
 void pop()  
 {  
         int i=0,j=size;  
         node *t;  
         while(i<j-1)  
         {  
                 t=deq();  
                 enq(t->d);  
                 i++;  
         }  
         t=deq();  
         printf("%d ",t->d);          
   
 }  
 void main()  
 {  
         push(1);  
         push(2);  
         push(3);  
         push(4);  
         push(5);  
         pop();  
         pop();  
         pop();  
         pop();  
         pop();  
   
           
 }  

Saturday, September 6, 2014

Clone a Binary Tree with Random Pointers Given a Binary Tree where every node has following structure.
struct node {
int key;
struct node *left,*right,*random;
}
The random pointer points to any random node of the binary tree and can even point to NULL, clone the given binary tree.
You can get code in c++ Here: https://gist.github.com/gk1721/36775e17719d460ac231

Wednesday, August 27, 2014

Linkage in c

 Translation unit:
  A program in a single file - single translation unit.

sharing functions and variable btw translation units : possible if variables and function have external linkage
by default global variable and non static functions (non static variables also) has external linkage so can be shared

Ex

file1.c                                                file2.c
int a=0;                                              extern int a;   //  refering to file1.c's a
void abc()                                          void ab()
{                                                         {
                                                                  abc();        //
                                                                  notshared();   // error can't access notshared
}                                                         }
static void notshared()                      
{


}

variable and functions which has internal linkage like static functions and variables can't be accessed in other files(Translation units).

No linkage :   variables within function

Linkage :
        1. External
        2. Internal
        3. No linkage

Saturday, August 2, 2014

Sorting: bubble, selection,insertion, quick, merge, counting sort programs in c

Bubble sort:

#include<stdio.h>

// compare adjacent elements and swap if needed until whole is not sorted
int arr[]={3,8,6,1,9,6,3,1,10,7,8,5,16};
int size;
void main()
{

size=sizeof(arr)/sizeof(int);
int out[size];
int i,j;
for(i=size-1;i>=0;i--)
{
for(j=0;j<i-1;j++)
{
if(arr[j]>arr[j+1])
{
int tmp;
tmp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=tmp;
}
}
}
printf("size= %d\n",size);
for(i=0;i<size;i++)
printf("%d ",arr[i]);
}


Selection sort:

#include<stdio.h>
//  find minimum and bring it to top
int arr[]={3,8,6,1,9,6,3,1,10,7,8,5,16};
int size;
void main()
{
size=sizeof(arr)/sizeof(int);
int out[size];
int i,j;
for(i=0;i<size-1;i++)
{
for(j=i+1;j<size;j++)
{
if(arr[i]>arr[j])
{
int tmp;
tmp=arr[i];
arr[i]=arr[j];
arr[j]=tmp;
}
}
}
printf("size= %d\n",size);
for(i=0;i<size;i++)
printf("%d ",arr[i]);
}

Insertion sort:

#include<stdio.h>
//  insert element at right place in list
int arr[]={8,3,6,1,9,6,3,1,10,7,8,5,16};
int size;
void main()
{

size=sizeof(arr)/sizeof(int);
int out[size];
int i,j,v;

for(i=1;i<size;i++)
{
v=arr[i];
j=i;
while(arr[j-1]>v&&j>=1)
{
arr[j]=arr[j-1];
j--;
}
arr[j]=v;
}
printf("size= %d\n",size);
for(i=0;i<size;i++)
printf("%d ",arr[i]);
}




------------------------------------------------------------------

Quick sort:

-----------------------------------------------------------------
#include<stdio.h>
int a[]={4,2,7,8,5,1,0,6};
int size;
void print()
{
int i;
for(i=0;i<size;i++)
printf("%d ",a[i]);
}
void swap(int left,int right)
{
int tmp=a[left];
a[left]=a[right];
a[right]=tmp;

}
int partition(int l,int r)
{
int x=a[l];
int left=l;
int right=r;
while(left<right)
{
while(a[left]<=x)
left++;
while(a[right]>x)
right--;
if(left<right)
swap(left,right);
}
a[l]=a[right];
a[right]=x;
//printf("\nPivot= %d  ",a[right]);
//print();
//printf("\n");
return right;
}
void quicksort(int l,int r)
{
// printf("%d %d\n",l,r);
int i;
if(r>l)
{

int p=partition(l,r);
quicksort(l,p-1);
quicksort(p+1,r);
}
}
void main()
{
size=sizeof(a)/sizeof(a[0]);
//print();
int p=0;
int l=0,r=size;
quicksort(l,r);
print();
}


----------------------------------------------------------

Merge Sort:

----------------------------------------------------------

#include<stdio.h>
int a[]={3,3,6,1,9,6,3,1,10,7,8,5,16};
int size;
int tmp[13];
void merge(int l,int m,int r)
{
int tmp[r-l+1];
int p=0;
int i=0,j=0;
if(a[l]>a[r])
{
for(i=m;i<r+1;i++)
tmp[p++]=a[i];
for(i=l;i<m;i++)
tmp[p++]=a[i];
}
else if(a[m]>a[m-1])
{
for(i=l;i<m;i++)
tmp[p++]=a[i];
for(i=m;i<r+1;i++)
tmp[p++]=a[i];
}
else
{
i=l;
j=m;
while((i<m)&&(j<r+1))
{
if(a[i]<a[j])
{
tmp[p++]=a[i++];
}
else if(a[i]>a[j])
{
tmp[p++]=a[j++];
}
else
tmp[p++]=a[i++];
}
if(i<m)
{
//printf("\nIn case 1\n");
int q;
for(q=i;q<m;q++)
{
tmp[p++]=a[q];
}
}
else if(j<r+1)
{
// printf("\nIn case 2p=%d\n",p);
int q;
for(q=j;q<r+1;q++)
{
tmp[p++]=a[q];
}
}

}
for(i=l;i<r+1;i++)
{
a[i]=tmp[i-l];
}
}
void mergesort(int l,int r)
{
int m;

if(r>l)
{
m=(l+r)/2;
mergesort(l,m);
mergesort(m+1,r);
merge(l,m+1,r);
}
}

void main()
{
size=sizeof(a)/sizeof(a[0]);
int l=0,r=size-1;
mergesort(l,r);
int i;
for(i=0;i<size;i++)
printf("%d ",a[i]);
}


--------------------------------------------------

Counting sort:

-------------------------------------------------
#include<stdio.h>
int a[]={1,5,6,4,8,9,3,8,0,10,16,21,6};
int size,max;
void main()
{
size=sizeof(a)/sizeof(a[0]);
int i;
int out[size];
max=0;
for(i=0;i<size;i++)
{
if(a[i]>max)
max=a[i];
}
int c[max+1];
for(i=0;i<max+1;i++)
{
c[i]=0;
}
for(i=0;i<size;i++)
{
c[a[i]]=c[a[i]]+1;
}
for(i=1;i<max+1;i++)
{
c[i]=c[i]+c[i-1];
}
for(i=size;i>=0;i--)
{
out[c[a[i]]-1]=a[i];
c[a[i]]=c[a[i]]-1;
}
for(i=0;i<size;i++)
{
printf("%d ",out[i]);
}
}

Insert records from a table to other table


Note:   While inserting records from a table to other table  values clause must not be used

Example:
     
           insert into highAchiever (name, age)  (select name, age from salesperson where salary > 100000);

Friday, August 1, 2014

SQL JOINS

              You have following tables 



SalespersonCustomer
IDNameAgeSalary
1Abe61140000
2Bob3444000
5Chris3440000
7Dan4152000
8Ken57115000
11Joe3838000
IDNameCityIndustry Type
4SamsonicpleasantJ
6PanasungoaktownJ
7SamonyjacksonB
9OrangeJacksonB
Orders
Numberorder_datecust_idsalesperson_idAmount
108/2/9642540
201/30/99481800
307/14/9591460
401/29/98722400
502/3/9867600
603/2/9867720
705/6/9897150
Given the tables above, find the following:

a. The names of all salespeople that have an order with Samsonic. 
solution:
SELECT distinct name FROM `salesperson` WHERE id in(select salesperson_id from customer,orders where id=cust_id AND name='Samsonic');
if you write  above query like:

SELECT distinct name FROM `salesperson` WHERE id=(select salesperson_id from customer,orders where id=cust_id AND name='Samsonic');
It is invalid query because subquery returning multiple records so it can't be compared. 



Insert multiple rows in mysql

MySql  :)


insert into customer values(4,'Samsonic','pleasant','J'),
(6,'Panasung','oaktown','J'),
(7,'Samony','jackson','B'),
(9,'Orange','Jackson','B');

Insert into Multiple rows in single query: SQL

Method 1 - Traditional InsertINSERT INTO #SQLAuthority (IDValue)VALUES (1'First');INSERT INTO #SQLAuthority (IDValue)VALUES (2'Second');INSERT INTO #SQLAuthority (IDValue)VALUES (3'Third');

TRUNCATE TABLE #SQLAuthority;
Method 2: INSERT…SELECT
INSERT INTO #SQLAuthority (IDValue)
SELECT 1'First'UNION ALLSELECT 2'Second'UNION ALLSELECT 3'Third';

TRUNCATE TABLE #SQLAuthority;
Method 3: SQL Server 2008+ Row Construction
-- Method 3 - SQL Server 2008+ Row ConstructionINSERT INTO #SQLAuthority (IDValue)VALUES (1'First'), (2'Second'), (3'Third');

Tuesday, July 29, 2014

Storage classes in c

Generally we don't specify storage classes while declaring variables in c, but compiler assume a storage class of a variable based on where it is declared. So variables have default storage classes.
But wait  what is storage class???
Let me tell you storage class is something  by which compiler identifies some physical location within computer where variable will be stored, there two options for storing variable CPU register and Memory.
Storage class determine where to store variable.
There are 4 storage classes defined by c language:
               1. Automatic storage class
               2. Register storage class
               3. Static storage class
               4 . External storage class
These classes define where to store variable physically, it's initial value, scope.

External storage class:

Features:-
Storage-                             memory
Default initial value-            Zero
Scope-                              Global
Life-                                  As long as the program's execution

Global variable use external storage class. They persists during execution of program. Global variable can also shared among files in c. Ex
  1. /* File One.c*/
  2. #include<stdio.h>
  3. int i=9;

             
  1. /*File :  two.c*/
  2. #include<stdio.h>
  3. #include"prog1.c"
  4. extern int i;
  5. void main()
  6. {
     printf("i=%d",i);
  1.  }  

                Output: 9
When a variable is declared as extern it belong to external storage class and compiler do not allocate memory for it, assumes that it exists in some other file. If global variable in above program not declared as extern even now it will work because global variable are by default use external storage class.
                  

Automatic storage class:

Features:
Storage                                            Memory
Default initial value                           Garbage value
Scope                                             Local
Life                                                 Till the Control remains in the scope

      Ex:   auto int a;
       1.  auto int i=1;
2.  {
3.      auto int i=3;
4.      Printf(“%d”,i);
5.  }
 Note - variable i in line 3 is not same as line because both are in different scopes.


Monday, July 28, 2014

PRINTF MCQs


1. printf(1+”%d”);

     It starts printing the String Skipping the number of Characters specified before ‘+’ sign

2. Backslash Characters in C
  1. \n - Newline [ Moves Cursor Position to Next Line ]
  2. \b - Back Space [ Moves Cursor Position to 1 character Back ]
  3. \r - Linefeed [ Moves Cursor Position to First Position in Same Line ]
     Example:
     1.  #include<stdio.h>  
2.  void main()  
3.  {  
4.  printf("\nDiicket");  
5.  printf("\bter");  
6.  printf("\rCr");  
    }
    Outout  : Cricket  

3. Two Strings in Printf
      Ex : printf("Computer","Programming")
   1.    Only First String Will be Accepted
      2.    If number of Strings are Seperated by "Comma" then it will accept only
           first Stringf      
    
    4. %d format specifier
 printf("%d %d %d",50,050,0x50);Output:50 40 80

why?
  1. Any number preceded with Zero (040,050,030) are considered as Octal Numbers
  2. Any number preceded with [ 0x / 0X ] (0x40,0x50,0x30) are considered as Hexadecimal Numbers
5. Printf inside printf in C
    printf("%d",printf("%d",printf("%d",num)));  
 
 Output: 134241

Printf Returns total number of Digits 




Tuesday, April 1, 2014

Dictionary Encoding Data compression in python

#Dictionary Encoding
str=input("Enter text to be encoded ")
count=None
s1=str
lst=[]
def find(x,lst):
    for i in range(0,len(lst)):
        if x==lst[i]:
            
            return i
    
    return -1
lst=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
#print(lst)
s=s1[0]
s2=""
for i in range(0,len(s1)-1):
    c=s1[i+1]
    x=s+c
    #print("s=",s,"c=",c,"s+c=",x,"list=",lst)
    if find(x,lst)!=-1:
        s=s+c
        
    else:
        
        print(find(s,lst)+1)
        lst.append(s+c)
        s=c
print(find(s,lst)+1)
input()