Thursday, April 9, 2015

Counting all unique characters in a given line, with less static memory....

After a very very log time, I am able to push something into my techBlog. If we see the number of posts per year, it is descending order only. That means, if you keep growing in years of experience, technical learnings is going to be less....!?!?!?

Recently, one of my friends asked me one question to write a program to count the number of occurances of charactaers in an given line with minimal memory. I mean, without using big array to count the characters.

int main(int argc, char **argv)
{
 char *p, *f=NULL;
 int cnt = 0,i=0, j=0, found = 0;

 p = argv[1];  //p will be the given array
 f = (char*)malloc(strlen(p)); //allocating the same size of the given array to use minimal memory
 if(f == NULL)
 {
   printf("Error\n");
 }
 memset(f, 0, strlen(f));

/* Start traversing the give n array when we find unique, count the same in the whole array and keep updating the count in respective index in the new array which is 'f'  */
 for(cnt = 0;cnt < strlen(p); cnt++)
 {
  for(i = 0; i < strlen(p); i++)
  {
   if(p[cnt] == p[i])
    f[cnt]++;
  }
 }

/* This is to print the new array , without duplicates */
/* For abcabc string, a=2, b=2, c=2, a=2, b=2, c=2 will be the final array and it should be printed as a=2, b=2, c=2 only */

 for(i=0; i less than strlen(p); i++)
 {
   for(j=0; j less than i; j++)
   {
    if(p[i] != p[j])
     continue;
    else
     found = 1;
   }
   if(!found)
   {
    printf("%c = %d\n", p[i], f[i]);
   }
   found = 0;
 }
 return 0;
}

Output:
 ./a.out asdcbascasdc
a = 3
s = 3
d = 2
c = 3
b = 1


I know this can be fine tuned but doing anyhow was my problem statement and done. Anybody can improve this and post to this blog or as a comment.

Thanks.