// JP opened flex table

Click to See Complete Forum and Search --> : Speeding up anagram


orage04
April 18th, 2004, 05:13 PM
Hi,
I have some code which produces all anagrams of the command line argument give to the program. This is fine but with slightly longer words this takes hours. I have recently been looking at ways to speed it up and multi-threading seemed a good idea.
Here is my code so far:



# include <iostream.h>
# include <string.h>
# include <conio.h>
# include <fstream.h>

// Few Prototypes

void rotate_array (char*,int) ;
void print_permutations(char*,int) ;

// Create A FileStream

////ifstream openfile("D:\\Documents and Settings\\Administrator\\My Documents\\wordlists\\enable1.txt");


// Max Number Of Elements

const int MAX_LEN = 20;

// The Counter

int counter = 0;

// Prints the different permutations of the array of elements
// recursively.

void print_permutations(char *array,int pos)
{ char store[MAX_LEN]; //
strcpy(store,array); // Save the array

for(int i=pos;i<strlen(array);++i)
{ rotate_array(array,pos); // Rotate the array
if(pos==strlen(array)-1)
{ cout<<array<<endl;
counter++; // Inc the counter
}

// call print_perm.. recursively

if((pos+1)<strlen(array))
print_permutations(array,pos+1);
}

strcpy(array,store); // Restore the array
}

int main(int argc,char *argv[])
{ if(argc>1)
{ print_permutations(argv[1],0);
cout<<endl<<"Number of permutations = "<<counter<<endl;
}
else
cout<<argv[0]<<" <elements for eg 1234.. or abcd...> ";
}

//
// This function rotates a part of the array
//

void rotate_array(char *array, int pos)
{ char temp = array[pos];
for(int i=pos;i<strlen(array);++i)
{ char temp2 = array[i+1];
array[i+1] = temp;
temp = temp2 ;
}
array[pos] = array[strlen(array)-1];
array[strlen(array)-1] = 0;
}

Is there a simple way of multi threading this, this seemed very complicated to do but i have never done any multi-threading before.

Thanks in advance.

j0nas
April 19th, 2004, 03:13 AM
Multithreading won't speed up your program (unless you have more than one CPUs installed). It will probably slow down your app, because of the extra overhead of context switching.

What I suggest is to look for parts of your code which can be optimized.

orage04
April 19th, 2004, 04:23 AM
Thanks for telling me, I would have spent ages trying to do it if you hadn't.

I finally decided after optimizing it as much as i could that the best thing was not to print the found angrams and just toprint the ones you wanted, without printing it became at least 10* faster.

Thanks for your help.

CJ1
April 20th, 2004, 04:11 PM
If you print in thread, then you'll get the best of both worlds. you'll need to buffer the results for the printing thread.

This is just your standard producer-consumer problem.

//JP added flex table