C++ Code: Detemine combinations of String by using STL
/*Combinations of String */
#include<iostream>
#include<string>
#include<map>
#include<vector>
#include<set>
#include<algorithm>
using namespace std;
typedef vector<string> vec_str;
typedef map<int,vec_str> map_vec_str;
bool mysort(string str1,string str2)
{
return str1.size()<str2.size();
}
void calculation(string str,map_vec_str &res_map)
{
int i,j,length,len,vl,sl;
string temp;
char ch;
length=str.size();
length--;
for(i=0;i<=length;i++)
{
temp="";
temp.insert(0,1,str[i]);
res_map[i].push_back(temp);
}
len=1;
vec_str vec;
while(len<=length)
{
ch=str[len];
for(i=0;i<len;i++)
{
vec=res_map[i];
vl=vec.size();
for(j=0;j<vl;j++)
{
temp=vec[j];
sl=temp.size();
temp.insert(sl,1,ch);
res_map[i].push_back(temp);
}
}
len++;
}
}
void combination(string str,vec_str &res_vec)
{
int i,j,mlen,vlen;
vec_str vec;
map_vec_str mymap;
set<string> st;
set<string>::iterator it;
calculation(str,mymap);
mlen=mymap.size();
for(i=0;i<mlen;i++)
{
vec=mymap[i];
vlen=vec.size();
for(j=0;j<vlen;j++)
st.insert(vec[j]);
}
for(it=st.begin();it!=st.end();it++)
res_vec.push_back(*it);
sort(res_vec.begin(),res_vec.end(),mysort);
}
void combination(string str,int r,vec_str &res_vec)
{
int i,j,mlen,vlen;
vec_str vec;
map_vec_str mymap;
set<string> st;
set<string>::iterator it;
calculation(str,mymap);
mlen=mymap.size();
for(i=0;i<mlen;i++)
{
vec=mymap[i];
vlen=vec.size();
for(j=0;j<vlen;j++)
{
if(vec[j].size()==r)
st.insert(vec[j]);
}
}
for(it=st.begin();it!=st.end();it++)
res_vec.push_back(*it);
}
int main()
{
vec_str ans_vec;
string str;
str="abaca";
cout<<"Determine all combination from 1 to string length size.."<<endl;
combination(str,ans_vec);
for(int i=0;i<ans_vec.size();i++)
cout<<ans_vec[i]<<endl;
ans_vec.clear();
cout<<endl<<"Determine r size combination from string.. For example: r is 3"<<endl;
combination(str,3,ans_vec);
for(int i=0;i<ans_vec.size();i++)
cout<<ans_vec[i]<<endl;
return 0;
}
Output:
Determine all combination from 1 to string length size..
a
b
c
aa
ab
ac
ba
bc
ca
aaa
aac
aba
abc
aca
baa
bac
bca
aaca
abaa
abac
abca
baca
abaca
Determine r size combination from string.. For example: r is 3
aaa
aac
aba
abc
aca
baa
bac
bca
Comments
Post a Comment