-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
anurag wrote:
hey can anyone help me in writing a code in c (function) that prints
all permutations of a string.please help
IIRC, this favour has been requested a number of times in recent weeks.
I wonder why the sudden interest in permuting strings using C
functions.
In any case, to give a concrete example of what R.H. discusses
elsethread, here's an attempt I made a few weeks ago, when the question
first came up. Take it as you will.
For the regulars: yes I know that answering a homework question is
frowned apon, and even worse is answering an algorithm question, but
this one piqued my interest. So, for my one freebie a year, I post this
code ;-)
==snip==
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void rotate(unsigned length, char *string)
{
char save;
save = *string;
while(--length)
{
*string=*(string+1);
++string;
}
*string = save;
}
void permute(unsigned length, char *string, unsigned depth)
{
if (length == 0)
printf("%s\n",string-depth);
else
{
unsigned count;
for (count = length ; count > 0; --count)
{
permute(length-1,string+1,depth+1);
rotate(length,string);
}
}
}
int main(int argc, char **argv)
{
while (--argc)
{
char *source = malloc(strlen(*++argv)+1);
if (source)
{
strcpy(source,*argv);
printf("\nPermuting \"%s\"\n",source);
permute(strlen(source),source,0);
free(source);
}
}
return EXIT_SUCCESS;
}
==snip==
- --
Lew Pitcher
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.3 (MingW32) - WinPT 0.11.12
iD8DBQFEv84lagVFX4UWr64RAq3YAKDBs4//FGSrc+zn7+duG2bRtCuRaQCfSnOS
mg6QbOGNExUVVsXBp5lQYD8=
=pYBy
-----END PGP SIGNATURE-----