Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is the best data-structure for iterating through arrangements of a string?

Lets say, we have string "ABCAD", now we need to iterate through all possible arrangement of this string in both clockwise and counter-clockwise direction.

My ugly implementation looks like this:

string s = "ABCAD";
string t ="";
 for(int i = 0; i < sz(s); i++){
    t = s[i];
  for(int j = i+1; ; j++){
      if((j) == sz(s)){
         j = 0;
        }
       if(j == i){
          break;
        }
       t+= s[j];
     }
     cout<<t<<" ";
   }
reverse(all(s));
 for(int i = 0; i < sz(s); i++){
    t = s[i];
  for(int j = i+1; ; j++){
      if((j) == sz(s)){
         j = 0;
        }
       if(j == i){
          break;
        }
       t+= s[j];
     }
     cout<<t<<" ";
   }

Output:

AHSAU HSAUA SAUAH AUAHS UAHSA UASHA ASHAU SHAUA HAUAS AUASH

I know that too naive,AFAIK a circular list would be a better choice, could somebody implement the same thing more efficiently using STL ?

like image 838
whacko__Cracko Avatar asked Feb 28 '23 13:02

whacko__Cracko


1 Answers

In pseudocode, I'd go this route:

function rearrange (string s) {
  string t = s + s;
  for (int i = 0; i < length(s); ++i)
    print t.substring(i, length(s));
}

input = "ABCAD"

rearrange(input);
rearrange(reverse(input));

There's probably a way to rewrite rearrange() using functors, but my STL-fu is rusty.

like image 131
Lars Avatar answered Mar 10 '23 11:03

Lars