Algorithm to find all possible permutations of a string or array

5.42K viewsProgramming
0

How can I implement a generic algorithm which generates all possible permutations of a string or array elements ?

Answered question
0

Here is another C program to achieve the same. 

It uses a macro N which is defined as of length 9 initially.

#include <stdio.h>
#include <string.h>
 #define N 9     /// 9 characters as of now
 // array which will hold the permuted combination
char table[N];
 void permute(int, int);
void display_table(int);
 int permute_count = 0;
   int main()
{
    printf("Please enter the string\n");
    gets(table);
     printf("\n\n");
    permute(1, strlen(table));
     printf("Total number of permutations is = %d\n", permute_count);
    return 0;
}
   void permute(int low, int high)
{
    char temp, tab[N];
    int j = 0, k = 0;
     if(low == high)
        display_table(high);
     else
        {
              for(j = 0; j < high; j++) tab[j] = table[j];
               for(k = low; k <= high; k++)
        {
              permute(low + 1, high);
             if(k != high)
                {
                      temp = tab[low - 1];
                      tab[low - 1] = tab[k];
                      tab[k] = temp;
                      for(j = 0; j < high; j++) table[j] = tab[j];
                }
        }
        }
   }
  void display_table(int num)
{
    int i = 0;
    for(i = 0; i < num; i++)
        putchar(table[i]);
     permute_count++;
     printf("\n");
}

Answered question
You are viewing 1 out of 2 answers, click here to view all answers.
Write your answer.

Categories