Thread: String Permutations

  1. #1
    Registered User
    Join Date
    Feb 2010
    Posts
    9

    String Permutations

    Hi, I was doing some practice problems and one of them is to find all the different string permutations of ABC.

    Here is my code which gives no errors or warnings but clearly my logic is wrong somewhere and I cannot find where.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    void swap(char *a, char *b){
    char temp;
    
    temp = *a;
    *a = *b;
    *b = temp;
    }
    
    
    
    
    void permute( char *str, int i, int n){
    
    int j, range = n - i;
    
     if (i == n)
         printf("%s\n", str);
     else{
    
          for( j = i; j <= range; j++){
          swap(&str[i],&str[n]);
          permute(str, i, j);
          swap(&str[i],&str[n]);}
    }
    }
    
    int main(void){
    
    
    char *ptr; 
    char string[] = "ABC";
    
    ptr = string;
    
    permute(ptr,0,2);
    return 0;}

  2. #2
    Registered User
    Join Date
    Feb 2011
    Posts
    44
    Quote Originally Posted by mrkrinkle View Post

    Code:
    void permute( char *str, int i, int n){
    
    int j, range = n - i;
    
     if (i == n)
         printf("%s\n", str);
     else{
    
          for( j = i; j <= range; j++){
          swap(&str[i],&str[n]);
          permute(str, i, j);
          swap(&str[i],&str[n]);}
    }
    }
    this might be just me, but i don't think you can call a function within its own definition?

  3. #3
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by synhyborex View Post
    this might be just me, but i don't think you can call a function within its own definition?
    Sure you can. It's called Recursion ...

    Cprogramming.com Tutorial: Recursion

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. char Handling, probably typical newbie stuff
    By Neolyth in forum C Programming
    Replies: 16
    Last Post: 06-21-2009, 04:05 AM
  2. Inheritance Hierarchy for a Package class
    By twickre in forum C++ Programming
    Replies: 7
    Last Post: 12-08-2007, 04:13 PM
  3. RicBot
    By John_ in forum C++ Programming
    Replies: 8
    Last Post: 06-13-2006, 06:52 PM
  4. Classes inheretance problem...
    By NANO in forum C++ Programming
    Replies: 12
    Last Post: 12-09-2002, 03:23 PM
  5. Warnings, warnings, warnings?
    By spentdome in forum C Programming
    Replies: 25
    Last Post: 05-27-2002, 06:49 PM