I have this code to generate lexicographic permutations. The following logic is used:
- Start from the increasing order arrangement of the chars in a given test string.
- To generate next lexicographic permutation:
a) find the rightmost character which is smaller than its next character. SAY A.
b) to the right of A, find the next larger character. SAY B. and swap A & B.
c) to the right of the original position of A, sort characters in an increasing order.
Algorithm ends when we get the last permutation. i.e. reverse of given test string.
my test string s = "0123456789"
Edit: On every single run of the program, i get a separate position of segmentation fault.
to get A:
int firstchar(string s){
int pos = s.length()-2;
for(int i=pos;i>=0;i--){
if(s[i]<s[i+1]){
pos = i;
break;
}
}
return pos;}
to get B and then recursive approach (qsort is a function from <cstdlib>
):
int ceilchar(string s, int fc){
int ceil = fc+1;
int diff=27;
for(int i=ceil;i<s.length();i++){
if(s[i]>s[fc] && s[i]-s[fc]<diff){
ceil = i;
diff = s[i]-s[fc];
}
}
return ceil;}
starting func:
void nextpermute(string& s){
int fc = firstchar(s);
int cc = ceilchar(s,fc);
swap(s,fc,cc);
sort(&s[fc]+1,&s[fc]+s.length()-fc);
if(s!="9876543210"){
cout<<s<<"\n";
nextpermute(s);
}
else
cout<<s<<"\n";}
call from main: nextpermute(test);
If the test string is "01234567"
or anything smaller than this, it works well. but if it is a string like
"012345678"
or "0123456789"
, then i get segmentation faults.
Please help!!
std::next_permutation
? – chrisstrcmp
withs.c_str()
instead ofoperator==
withs
? You've managed to take safe code and make it unsafe. – chris