I've been working on the 2nd Beginners (Help-Free)Programming Challenge of this very same site, and could use some help completing. I have adapted a snippet (by jon guthrie) for a program to permutate a user inputted string.
Thanks for the help. UC
Code:
/*
** PERMUTE.C - prints all permutations of an input string
**
** adapted from public domain demo by Jon Guthrie for J. Uslander (4/1/2008).
**
*/
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
int charcmp(char *, char *);
void permute(char *, int, int);
char *string;
int main(void)
{
printf("Enter a single word string, using only letters and no spaces.\n");
fgets(string, 15, stdin);
int length;
length = strlen(string);
if (length != 0 && length <=15)
{ /* It only works if they're printed in order */
qsort(string, length, 1, (int(*)(const void *, const void *))charcmp);
permute(string, 0, length);
return 0;
}
else {
printf("This program only accepts strings of length 1 letter and not more than 14 letters.\n");
return(0);
}
/*
** This function prints all of the permutations of string "array"
** (which has length "len") starting at "start."
*/
void permute(char *array, int start, int len)
{
int j;
char *s;
if(start < len)
{
if(NULL == (s = malloc(len + 1))) /* Bug fixed by Stephan Wilms */
{
printf("\n\nMemory error!!!\a\a\n");
abort();
}
strcpy(s, array);
for(j=start ; j<len ; ++j)
{
int temp;
if((j == start) || (s[j] != s[start]))
{ /* For each character that's different */
/* Swap the next first character with... */
/* the current first */
temp = s[j];
s[j] = s[start];
s[start] = temp;
permute(s, start+1, len);
}
}
free(s);
}
else puts(array);
}
int charcmp(char *a, char *b)
{
return(*a - *b);
}
I tried to compile using code::blocks and was told there was an error in the charcmp function.
Thanks again for your help. UC