Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ algorithm for N! orderings

I have a list of N items and I am wondering how I can loop through the list to get every combination. There are no doubles, so I need to get all N! orderings. Extra memory is no problem, I'm trying to think of the simplest algorithm but I'm having trouble.

like image 817
Stuart Avatar asked Jan 26 '10 19:01

Stuart


3 Answers

See std::next_permutation   

like image 130
BlueRaja - Danny Pflughoeft Avatar answered Sep 27 '22 21:09

BlueRaja - Danny Pflughoeft


Expanding on others' answers, here's an example of std::next_permutation adapted from cplusplus.com

#include <iostream>
#include <algorithm>
using namespace std;

void outputArray(int* array, int size)
{
  for (int i = 0; i < size; ++i) { cout << array[i] << " "; }
}

int main ()
{
  int myints[] = { 1, 2, 3, 4, 5 };
  const int size = sizeof(myints);

  cout << "The 5! possible permutations with 5 elements:\n";

  sort (myints, myints + size);

  bool hasMorePermutations = true;
  do
  {
    outputArray(myints, size);
    hasMorePermutations = next_permutation(myints, myints + size);
  }
  while (hasMorePermutations);

  return 0;
}
like image 41
Bill Avatar answered Sep 27 '22 21:09

Bill


C++ STL has next_permutation for this purpose.

like image 38
sud03r Avatar answered Sep 27 '22 22:09

sud03r