Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does next_permutation skip some permutations?

Tags:

Why doesn't this simple function output all permutations of the inputted 5 letter string? I think there should be 120 and it only outputs 90.

#include <iostream> #include <vector> #include <algorithm> #include <string> using namespace std;  // Creates permutation lists for strings vector<string> createdcombos2(string letters) {      vector<string> lettercombos;          cout << "Letters are: " << letters << endl; //input string      do          lettercombos.push_back(letters);             while(next_permutation(letters.begin(), letters.end()));          cout <<"Letter combos: " << endl;  //print out permutations      for (auto i : lettercombos)         cout << i << endl;     cout << endl << lettercombos.size() << endl; //number of permutations      return lettercombos; }   int main()  {     string letters = "gnary";      vector<string> lettercombos;      lettercombos = createdcombos2(letters); } 
like image 433
Austin Avatar asked Jul 07 '15 01:07

Austin


People also ask

How next_ permutation works?

Next_permutation transforms the range of elements [first, last) into the lexicographically next greater permutation of the elements. […] If such a permutation exists, next_permutation transforms [first, last) into that permutation and returns true.

What is the time complexity of next_ permutation?

std::next_permutation Different permutations can be ordered according to how they compare lexicographically to each other. The complexity of the code is O(n*n!)

What does next_ permutation function do in c++?

C++ Algorithm next_permutation() function is used to reorder the elements in the range [first, last) into the next lexicographically greater permutation. A permutation is specified as each of several possible ways in which a set or number of things can be ordered or arranged. It is denoted as N!

What does next permutation mean?

The lexicographically next permutation is basically the greater permutation. For example, the next of “ACB” will be “BAC”. In some cases, the lexicographically next permutation is not present, like “BBB” or “DCBA” etc. In C++ we can do it by using a library function called next_permutation().


1 Answers

To return all permutations in a loop until next_permutation returns false, the vector must be sorted before the start of the loop. next_permutation returns the permutations in ascending order. So if you start off with an unsorted vector, it will begin part way through the series of permutations.

std::sort(letters.begin(), letters.end()); do      lettercombos.push_back(letters);         while(next_permutation(letters.begin(), letters.end()));   
like image 140
samgak Avatar answered Oct 13 '22 08:10

samgak