home *** CD-ROM | disk | FTP | other *** search
/ Programmer 7500 / MAX_PROGRAMMERS.iso / INFO / C / R_LA4_02.ZIP / ANAGRAM.C < prev    next >
Encoding:
C/C++ Source or Header  |  1988-01-20  |  1.7 KB  |  54 lines

  1. /* ANAGRAM.C - From page 584 of "Microsoft C Programming for    */
  2. /* the IBM" by Robert Lafore. Creates all possible letter ar-   */
  3. /* rangements in a given word. The version in the book doesn't  */
  4. /* work correctly. The line I changed is marked in the comments */
  5. /* in the source code. The printf() was added because in the    */
  6. /* recursive function rotate is called before the original      */
  7. /* word is printed.                                             */
  8. /****************************************************************/
  9.  
  10. char word[40];
  11. int length;
  12. main()
  13. {
  14.  
  15.    printf("\n\nType word: ");
  16.    gets(word);
  17.    length = strlen(word);
  18.    printf("%s\n", word);               /*** ADDED TO SOURCE ***/
  19.    permute(0);
  20. }
  21.  
  22. /* permute */  /* prints all permutations of word */
  23.                /* word begins at position startperm */
  24. permute(startperm)
  25. int startperm;
  26. {
  27. int j;
  28.  
  29.    if(length - startperm < 2)       /* exit if one char */
  30.       return;
  31.    for(j = startperm; j < length - 1; j++)  {   /*# chars in word-1*/
  32.       permute(startperm + 1);       /*permutes all but first*/
  33.       rotate(startperm);            /*rotate all chars*/
  34.       printf("%s\n", word);
  35.    }
  36.    permute(startperm + 1); /*restore word to*/
  37.    rotate(startperm);               /*form at entry*/
  38. }
  39.  
  40. /* rotate() */    /*rotates word one char left*/
  41.                   /*word begins at char pos startrot*/
  42. rotate(startrot)
  43. int startrot;
  44. {
  45. int j;
  46. char ch;
  47.  
  48.    ch = word[startrot];             /*save first char*/
  49.    for(j = startrot; j < length - 1; j++) /*move other chars left*/
  50.       word[j] = word[j + 1];              /* one position */
  51.    word[length - 1] = ch;
  52. }
  53.  
  54.