Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
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
- if s[i] > s[i - 1]), then:
- t := s[i - 1]
- 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
Advertisements
