The C language implements typing a string and printing out all permutations of the characters in that string

  • 2020-04-02 02:44:55
  • OfStack

The example of this article describes the C language to input a string after printing out all the permutation of the characters in the string method, belongs to the mathematical permutation problem. It's a very useful algorithmic trick. Share with you for your reference. The specific implementation method is as follows:

For example, the input string ABC outputs all the strings ABC, acb, bac, bca, cab, and cba that can be arranged by the characters a, b, and c.

C language implementation code is as follows:


 
#include <iostream>
#include <algorithm>

using namespace std;

char array[] = {'a', 'b', 'c'};
const int size = sizeof array / sizeof *array;

void Perm(char *array, int pos, int last) 
{ 
 if (pos == last) {
 copy(array, array + size, ostream_iterator<char>(cout, ""));
 cout << endl;
 } 
 else { 
 for(int i = pos; i <= last; i++) { 
  swap(array[i], array[pos]); 
  Perm(array, pos + 1, last); 
  swap(array[i], array[pos]); 
 } 
 }
}

void main()
{
 Perm(array, 0, 2);
}

It is hoped that the examples described in this paper will be helpful to the learning of C program algorithm design.


Related articles: