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
    • if s[j]
    • Come out from the loop
  • t := s[i - 1]
  • s[i - 1] = s[j - 1]
  • s[j - 1] = t
  • for i
  • t := s[i]
  • s[i] := s[n - 1]
  • s[n - 1] = t
  • return 1
  • for initialize i := 0, when i
  • 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
    • 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 
    #include 
    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 ' : ' ');
        } 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: 2021-10-08T11:19:50+05:30

    6K+ Views

    Kickstart Your Career

    Get certified by completing the course

    Get Started
    Advertisements