C program to find permutations of given strings


Suppose we have few strings in an array. We shall have to find all permutations of them in different line.

So, if the input is like strings = ["abc", "def", "ghi"], then the output will be

abc def ghi
abc ghi def
def abc ghi
def ghi abc
ghi abc def
ghi def abc

To solve this, we will follow these steps −

  • Define a function next_permutation(), this will take n, string array s,
  • for initialize i := n - 1, when i > 0, update (decrease i by 1), do:
    • if s[i] > s[i - 1]), then:
      • j := i + 1
    • for j < n, update (increase j by 1), do:
      • if s[j] <= s[i - 1]), then:
        • Come out from the loop
      • t := s[i - 1]
    • s[i - 1] = s[j - 1]
    • s[j - 1] = t
    • for i < n - 1, update (increase i by 1), (decrease n by 1), do:
      • t := s[i]
      • s[i] := s[n - 1]
      • s[n - 1] = t
    • return 1
  • for initialize i := 0, when i < n - 1, update (increase i by 1), (decrease n by 1), do:
    • t := s[i]
    • s[i] := s[n - 1]
    • s[n - 1] = t
  • return 0
  • From the main method do the following
  • do the following infinitely until next_permutation(n, strings) is 0{
    • for initialize i := 0, when i < n, update (increase i by 1), do:
      • display strings[i] then (if i is same as n - 1, then go to next line, otherwise print blank space

Example

Let us see the following implementation to get better understanding −

#include <stdio.h>
#include <string.h>
int next_permutation(int n, char **s){
    for (int i = n - 1; i > 0; i--)
        if (strcmp(s[i], s[i - 1]) > 0){
            int j = i + 1;
            for (; j < n; j++)
                if (strcmp(s[j], s[i - 1]) <= 0)
                    break;
            char *t = s[i - 1];
            s[i - 1] = s[j - 1];
            s[j - 1] = t;
            for (; i < n - 1; i++, n--){
                t = s[i];
                s[i] = s[n - 1];
                s[n - 1] = t;
            }
            return 1;
        }
    for (int i = 0; i < n - 1; i++, n--){
        char *t = s[i];
        s[i] = s[n - 1];
        s[n - 1] = t;
    }
    return 0;
}
int main(){
    char *strings[] = {"abc", "def", "ghi"};
    int n = 3;
    do{
        for (int i = 0; i < n; i++)
            printf("%s%c", strings[i], i == n - 1 ? '
' : ' ');     } while (next_permutation(n, strings)); }

Input

{"abc", "def", "ghi"}

Output

abc def ghi
abc ghi def
def abc ghi
def ghi abc
ghi abc def
ghi def abc

Updated on: 08-Oct-2021

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements