Monday, June 30, 2014

C++ Default Constructor Case 1

#include "stdafx.h"
#include<string>
#include<iostream>
using namespace std;

class A{
public:
A(string a){ cout << "lovely me "; }
};
class B{
A a1;
string name;
};

int _tmain(int argc, _TCHAR* argv[])
{
B b1;
return 0;
}


Output :
Error 1 error C2512: 'B' : no appropriate default constructor available

Explanation :

There are four types of compiler generated functions :
1.)Copy Constructor
2.)Assignment Operator
3.) Default constructor
4.) Default destructor.

And these functions are generated only if there is need for it.
For example, like in the code given above, compiler would try to generate a default constructor for B ( B b1)
which in turn would call the default constructor for its data members i.e. for the statement A a1.
So In class A, compiler would try to find for a default constructor, but it finds one constructor there with  a parameter. So it is not able to find a default constructor for A. and hence it fails to generate a default constructor for B as well. Hence the error.
Some compilers may throw an information like the
candidates are B::B(const B&)
This is for the reason that compiler would find copy constructor as the next possible match as copy constructor is also generated by compiler itself.

To remove the error :

class A{
public:
A(){ cout << "lovely me "; }
};

Saturday, June 28, 2014

Setting up PhoneGap for Hello World!

PhoneGap is a mobile development framework that allows developers to build applications for a variety of mobile platforms, using web technologies such as HTML, CSS, and JavaScript.
An application developed using PhoneGap can be deployed to multiple mobile platforms without rewriting the code.

I have been trying to prepare the basic set up for a Hello World application on PhoneGap. It took me quite many efforts to do that. I could not find one single reference that could help me from start to end. So here am I trying to put my experience of making it stand up and run.

Recent Phonegap requires installation of
1.)NodeJS
http://phonegap.com/install/
Run the command given C:\> npm install -g phonegap
 comm This might give an error as to install git.
Install git. I did it from http://git-scm.com/download/win. Once downloaded click it, and it will take you to its set up wizard. Keep following the next.
I assume you have Java and Android SDK installed. In case you don't have that, please install Java 
http://www.oracle.com/technetwork/java/javase/downloads/index.html?ssSourceSiteId=otnjp
 Android SDK.
https://developer.android.com/sdk/index.html - Whole bundle would install the sdk and eclipse. Other apis can be downloaded by starting the SDK manager as and when required.
You might also require to install Apache Ant and Ruby.
Apache ant can be downloaded from
http://ant.apache.org/bindownload.cgi . Download the zip archive
I downloaded Ruby from http://rubyinstaller.org/. Click the download button.
Set environment variables in Control Panel.I have set as following according to how I have things onto my system. Following are USER VARIABLES in System-> Advanced Settings->Environment Variables
ANDROID_HOME
C:\adt-bundle-windows-x86-20140321\adt-bundle-windows-x86-20140321\sdk
ANT_HOME
C:\apache-ant-1.9.4
JAVA_HOME
C:\Program Files (x86)\Java\jdk1.8.0_05
Make sure JAVA_HOME is pointing to jdk directory.
I have added      %JAVA_HOME%/bin .  in PATH

I have the following paths as well in my PATH under system variables , each separated by ;
C:\Program Files\nodejs\;
C:\Ruby200\bin;C:\apache-ant-1.9.4\bin;
C:\adt-bundle-windows-x86-20140321\adt-bundle-windows-x86-20140321\sdk\platform-tools;
C:\adt-bundle-windows-x86-20140321\adt-bundle-windows-x86-20140321\sdk\tools;
C:\Program Files (x86)\Java\jdk1.8.0_05

Once all this set up is done,and class paths are set,run following commands from cmd prompt.
C:\>npm install -g cordova
Create Helloworld app as 
  $ cordova create hello com.example.hello HelloWorld
This would create a Hello app in C:/
Now do  :   cd hello
 Run the following command
cordova platform add android
Now project can be opened in Eclipse. I did it using Open->Import -> Browsing to C:/Hello
Make sure that it imports both the projects - Helloworld as well as HelloWorld-CordovaLib.
Check you must see Cordovalib green-checked 


Now clean HelloWorld-cordovaLib and build and then clean Helloworld and build.
Launch an emulator through AVD manager. Now run the HelloWorld app.
Output should be something of this kind. Way to go now with Phonegap.
Leave me a comment if you find this article helpful. 















Thursday, March 15, 2012

Reverse a linked list every "given num" nodes

#include<stdio.h>
#include<stdlib.h>
struct node
  {
    int val;
    struct node* next;
  };
struct node *current=NULL,*temp=NULL,*prev=NULL,*header1=NULL,*header2=NULL,*header3=NULL;
struct node* head=NULL,*A=NULL,*B=NULL,*C=NULL,*last=NULL;
struct node* createlist(struct node* header);
void print(struct node* header);
main()
 {
int number;
   int x,sum;
   char ch;
   int i=1;
   int flag=1;
   header1=malloc(sizeof(struct node));
   header1->next=NULL;
   printf("\n enter the value to be put in the header node" );
   scanf("%d",&x);
   header1->val=x;
   createlist(header1);
   print(header1);
   printf("\n enter after how many nodes reversal");
   scanf("%d",&number);
   A=B=C=head=header1;
   while(B!=NULL)
   {
       for(i=1;i<=number-1;i++)
       {
         if(A==head)
         {
             A=A->next;
             printf("\n a data %d",A->val);
         }

            B=A->next;
            A->next=head;
            C->next=B;
            head=A;
            A=B;
            if(last!=NULL)
               last->next=head;
       }
       last=C;       C=A;
       if (flag) { header1=head; flag=0;}
       head=A;
   }
   print(header1);
 }
struct node* createlist(struct node* header)
{
    int x;char ch;
     current=header;
   temp=header;
   do
    {
      current=malloc(sizeof(struct node));
      printf("\n enter the value to be put in it \n");
      scanf("%d",&x);
      current->val=x;
      temp->next=current;
      temp=current;
      getchar();
      printf("\n want  MORE \n");
      scanf("%c",&ch);
      printf("\n char entered is %c",ch);
    }while(ch=='y');
  current->next=NULL;
  current=header;
}

void print(struct node* header)
{
current=header;
 while(current!=NULL)
  {
   printf("\n value is %d",current->val);
   current=current->next;
  }
}

Thursday, March 8, 2012

Find substring

Write a C program that takes two strings (string a, string b) and gives the first occurrence of string b in string a.

#include<stdio.h>
#include<stdlib.h>
#include<stddef.h>
#include<string.h>
int comparelen(char *st1, char* st2);
void main()
{
    int len1,len2;
    char str1[]="ABCDEFGHIJ";
    char str2[]="HIJK";
    char* ptr=str1;
    int t=1,pos=0;
    printf("\n strings are %s %s",str1,str2);
    getchar();
    len1=strlen(str1);
    len2=strlen(str2);
        printf("\n strings are %d %d",len1,len2);
        getchar();               
        getchar();
        while(pos<=(len1-len2) && (t!=0))
        {
            t=comparelen(ptr,str2);
            printf("\n pos and t %d %d",pos,t);
            if(t==-1)
            {
                ptr++;
                pos=pos+1;
            }
            else if(t==0)
            {
                printf("\n found at pos %d",pos);
                getchar();
            }
        }
        if(t==-1)
        {
            printf("\n not found at all");
            getchar();
        }
}

int comparelen(char *st1, char* st2)
{
    for(int i=0;i<strlen(st2);i++)
    {
        if(st1[i]==st2[i])
        {
            st1++; st2++;
        }
        else
            return -1;
    }
    return 0;
}

Monday, February 13, 2012

Merge sort

Merge sort
This one is also based on divide and conquer strategy just like quick sort.Dividing the array into two subarrays of size n/2. Then recursively solve two subarrays and then combine them using merge.Keep dividing the array recursively in 2 parts till left with subarray of one element.Then call merge to combine two subarrays.Starting with combining two subarrays of size 1, merge compares two to put them in sorted sequence.
Try the following snippet:
#include<stdio.h>
#define MAX_SIZE 10
void m_sort(int numbers[], int temp[], int left, int right);
void merge(int numbers[], int temp[], int left, int mid, int right);
void main()
{
 int arr[MAX_SIZE];
 int temp[MAX_SIZE];
 int i,pos;

 for(i=0;i<MAX_SIZE;i++)
 {
  printf("\n enter the element : : %d ",i+1);
  scanf("%d",&arr[i]);
 }
m_sort(arr, temp, 0, MAX_SIZE - 1);

  for(i=0;i<MAX_SIZE;i++)
 {
  printf("\n element %d",arr[i]);
 }
  getchar();
  getchar();

}

void m_sort(int numbers[], int temp[], int left, int right)
{
        int mid;
        if (right > left)
        {
            mid = (right + left) / 2;
            m_sort(numbers, temp, left, mid);
            m_sort(numbers, temp, mid+1, right);
            merge(numbers, temp, left, mid+1, right);
        }
}

void merge(int numbers[], int temp[], int left, int mid, int right)
{
            int i, left_end, num_elements, tmp_pos;
            left_end = mid - 1;
            tmp_pos = left;
            num_elements = right - left + 1;
        while ((left <= left_end) && (mid <= right))
        {
            if (numbers[left] <= numbers[mid])
                {
                        temp[tmp_pos] = numbers[left];
                        tmp_pos = tmp_pos + 1;
                        left = left +1;
                }
                else
                {
                        temp[tmp_pos] = numbers[mid];
                        tmp_pos = tmp_pos + 1;
                        mid = mid + 1;
                }
        }

        while (left <= left_end)
                {
                        temp[tmp_pos] = numbers[left];
                        left = left + 1;
                        tmp_pos = tmp_pos + 1;
                }
        while (mid <= right)
                {
                        temp[tmp_pos] = numbers[mid];
                        mid = mid + 1;
                        tmp_pos = tmp_pos + 1;
                }
                for (i = 0; i <= num_elements; i++)
                {
                    numbers[right] = temp[right];
                        right = right - 1;
                }
        }

Quick Sort

Quick Sort
Worst case = theta (n2)
average case thete(nlogn)
It works on divide and conquer strategy.
Divide an array A[p...r] in A[p....q-1] and A[q+1....r] such that each element in A[p...q-1] is less than A[q] and those in A[q+1...r] are greater than A[q].
Sort the two subarrays recursively.
Pivot element is chosen against which comparisons are made and two regions are maintained which contain elements less than the pivot element and other region contains elements greater than it. At last pivot element is swapped with the element at the position next to region 1.


Try following code snippet:


#include<stdio.h>
#define MAX_SIZE 10
 void Quick_sort(int *a,int p, int r);
  int Partition(int *a,int start,int end);
void main()
{
 int arr[MAX_SIZE];
 int i,pos;

 for(i=0;i<MAX_SIZE;i++)
 {
  printf("\n enter the element : : %d ",i+1);
  scanf("%d",&arr[i]);
 }

 Quick_sort(arr,0,MAX_SIZE-1);
  for(i=0;i<MAX_SIZE;i++)
 {
  printf("\n element %d",arr[i]);
 }
  getchar();
  getchar();

}

void Quick_sort(int *a,int p, int r)
 {
     int index;
     if(p<r)
     {
        index=Partition(a,p,r);
         Quick_sort(a,p,index-1);
         Quick_sort(a,index+1,r);
     }
 }

 int Partition(int *A,int start,int end)
 {
int x=A[end];
int i =start-1;
int temp;
for(int j=start;j<end;j++)
{
  if(A[j]<=x)
     {
  i=i+1;
temp=A[i];
A[i]=A[j];
A[j]=temp;

}
}
temp=A[i+1];
A[i+1]=A[end];
A[end]=temp;
return i+1;
 }


Sunday, February 12, 2012

Heap Sort

Heap - It is almost an array object that is almost complete binary tree where it is filled on all levels except possibly the lowest.
Max heap and min heap are the two kind of heaps.
Max-Heap is the one which has the largest element at the root.
A[Parent(i)]>= A[i]

For Heap sort
Max Heapify : Left(i) and Right(i) are max heaps but A[i] may be smaller than its children. This process aims at sinking down a[i] to its appropriate position. Element at root is compared with elements in left and right and is swapped with the larger of two.

Building heap out of the array involves doing Max-heapify from pos=n/2-1 to 0 as all the other nodes in the tree are leaves and hence are one element heap only.Property of max-heap has to be maintained at all the child nodes also, if there are any.

Heapsort works by maintaining a max heap of the array. Thus the largest element is at the root. Swap the root element with the one at A[heapsize]. Thus decreasing the heap size by 1. Now let the element which  reached the root sink to its appropriate position using Max_heapify. Keep repeating till we have two elements in last. The array will go sorted in its position

Try the following snippet :

#include<stdio.h>
#define MAX_SIZE 10
void build_max_heap(int *a,int j);
int heap_size=MAX_SIZE;
void main()
{
 int arr[MAX_SIZE];
 int arr1[MAX_SIZE];
 int i,pos;

 for(i=0;i<heap_size;i++)
 {
  printf("\n enter the element : : %d ",i+1);
  scanf("%d",&arr[i]);
 }

 for(pos=((heap_size/2)-1);
pos>=0;pos--)
 {
   build_max_heap(arr,pos);
 }

for(i=0;i<MAX_SIZE;i++)
 {
    printf("\n arr[0] %d",arr[0]);
    arr1[i]=arr[0];
    heap_size=heap_size-1;
    arr[0]=arr[heap_size];
    printf("\n arr1[i] %d arr[0] %d",arr1[i],arr[0]);
    build_max_heap(arr,0);
 }

 for(i=0;i<MAX_SIZE;i++)
 {
  printf("\n element is %d",arr1[i]);
 }
 getchar();
 getchar();

}

void build_max_heap(int *a,int j)
{
 int largest;
 int left,right,temp;
 //int sub=diff;
 largest=j; 
 left=2*(j+1)-1;
 right=2*(j+1);
 printf("\n j %d a[j]%d ",j,a[j]);
 //printf("\n MAX_SIZE-diff %d ",MAX_SIZE-sub);

 if(left < (heap_size))
        printf("\n left %d a[left] %d",left,a[left]);
 if(right < (heap_size))
        printf("right %d a[right] %d",right,a[right]);
 if((left >=(heap_size)) && (right >=(heap_size)))
         return;
 if(left<(heap_size) && a[left]>a[j])
     {
       printf("\n in left ");
       largest=left;
     }
  
 if(right<(heap_size) && a[right]>a[largest])
     {
       printf("\n in right");
       largest=right;
     }
   temp=a[j];
   a[j]=a[largest];
   a[largest]=temp;

   if(j!=largest)
       build_max_heap(a,largest);

 return;
}