Monday, 4 September 2017

Find Subsets of Given String


Method I:
       Can find substring for any length of string because we are taking binary number as string while Conversion itself

#include<stdio.h>
#include<string.h>
#include<math.h>

char *GetBinary(int dec);

int main()
{
 int i,j,len,count=0,no_of_zeros;
 char str[20],temp[20],binary[20];
 printf("Enter a string\n");
 gets(str);
 len=strlen(str);
 printf("Subsets of Given String are");
 for(i=0;i<(pow(2,len));i++)//2^len is the number of subsets for given length.
 {
  strcpy(binary,GetBinary(i));
  no_of_zeros=len-strlen(binary);//Since zeros will not be there before single digits and double etc depending on length of binary number.

 //To compensate them we used here
  for(j=0;j<len;j++)
  {
         if(j>=noofzeros)
        {
          if(binary[j-no_of_zeros]!='0')
           printf("%c",str[j]);
        }
  }
        printf("\n");
 }
 return(0);
}

char *GetBinary(int dec)
{
 int temp,i,j=1,k=0;
 char binary[20];
 temp=dec;
 while(temp!=0)
 {
   i=temp%2;
      binary[k]=i+'0';
   temp=temp/2;
      j=j*10;
      k++;
 }
 binary[k]='\0';
 return(strrev(binary));
}

Method II:
       Can find subsets for smaller strings as we are taking binary number as integer
 
#include<stdio.h>
#include<string.h>
#include<math.h>

int GetBinary(int dec);

int main()
{
 int i,j,binary,len,count=0,tempLen;
 char str[20],temp[20];
 printf("Enter a string\n");
 gets(str);
 len=strlen(str);
 for(i=1;i<(pow(2,len));i++)//2^len is the number of subsets for given length
 {
  binary=GetBinary(i);
  sprintf(temp, "%d", binary);//To convert integer to string
  tempLen=len-strlen(temp);
  for(j=0;j<len;j++)
  {
   if(j>=tempLen)
   {
    if(temp[j-tempLen]!='0')
       printf("%c",str[j]);
   }
  }
  printf("\n");
 }
return 0;
}

int GetBinary(int dec)
{
 int temp,i,j=1,binary=0;
 temp=dec;
 while(temp!=0)
 {
   i=temp%2;
      binary=binary+(i*j);
   temp=temp/2;
      j=j*10;
 }
 return(binary);
}

Input :
Tea
Output:
T

a

Te
Ta

ea
Tea


Input :
Help
Output :
H
e
l
p
He
Hl
Hp
el
ep
lp
Hel
Hep
Hlp
elp
Help

No comments:

Post a Comment