Friday, May 18, 2012

Intreview Question: Given AAABBGFF should get an output 3{A} 2{B}1{G}2{F}

#include
#include
#include
typedef struct compressed{
int a;
char c;
}compressed;

int main()
{
    int i = 0,j =0,count=0;
    compressed *com = (compressed*)malloc(10*sizeof(compressed));
    char *string = "AAABBCGGAA";// Your test string hear

while(i<strlen(string))
{
    if(string[i]==string[i+1])++count;
    else{
    com[j].c=string[i],com[j].a = count+1;
    ++j,count=0;
    }
 ++i;
}
for(i=0;i<j;++i)
{

printf("%d{%c}",com[i].a,com[i].c);

}
    return 0;

}

Wednesday, May 16, 2012

Program to sort the array of integers with out altering the original array elements and with out creating another integer array


Write a program that reads integers from the keyboard and places them in an array. The program then will sort the array into ascending and descending order and print the sorted lists. The program must not change the original array or create any other integer arrays. The solution to the problem requires two pointer arrays as shown in the example the first pointer array is rearranged so that it points to the data in ascending sequence. The second pointer array is rearranged so that it points to the data in descending sequence.

#include
#include
#define length 10


void swap(int **a, int **b)
{
  int *t=*a; *a=*b; *b=t;
}
void sort(int **arr, int beg, int end)
{
  if (end > beg + 1)
  {
    int piv = *arr[beg], l = beg + 1, r = end;
    while (l < r)
    {
      if (*arr[l] <= piv)
        l++;
      else
        swap(&arr[l], &arr[--r]);
    }
    swap(&arr[--l], &arr[beg]);
    sort(arr, beg, l);
    sort(arr, r, end);
  }
}

int main()
{
   int **asc,**des,a;
    int i=0;
    int **inputs;
 //memory allocation for pointer to pointer
inputs = (int**)malloc(10*sizeof(int*));
asc = (int**)malloc(10*sizeof(int*));
des = (int**)malloc(10*sizeof(int*));
printf("Ender data to be sorted\n");
//read
for(i=0;i<10;++i)
{
    scanf("%d",&a);
    asc[i] = (int*)malloc(sizeof(int));//memory allocation for each
    des[i] = asc[i];
   *asc[i] = a;
}

//int testarray[10] ={1,2,5,6,4,3,7,8,9,10};
for(i=0;i<10;++i)
{
    inputs[i] = asc[i];

}

sort(asc,0,10);
for(i=0;i<10;++i)
{
    des[i] = asc[length-i-1];

}
printf("--------------------------------------------------\n");
printf("\t\tTable of sorted data\n");
printf("--------------------------------------------------\n");
printf("|\tINPUT \t|\tASC \t|\tDSC\t|\n");
printf("--------------------------------------------------\n");
for(i=0;i<10;++i)
{
    printf("|\t%d\t|\t%d\t|\t%d\t|\n",**inputs++,*asc[i],*des[i]);

}
printf("--------------------------------------------------\n");

    return 0;
The out put of the above program will look like this.