Public Group

# Get all array arrangements

This topic is 2772 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I can't wrap my head around this particular problem, so hopefully someone can help;

Let's say I have an array of integers;
{ 1, 2, 3, 4, 5 }

I want to be able to get all possible arrangements of the array elements so, for example, I get;

{ 1, 2, 3, 4, 5 }
{ 2, 1, 4, 2, 5 }
{ 5, 4, 3, 2, 1 }
{ 1, 2, 5, 4, 3 }
etc..

Can anyone help me out with this?

##### Share on other sites
A terms for you to search for is permutation. Specifically, you want to list all permutations. In C++, there is a standard library function for it already.
[source]
#include <iostream>
#include <algorithm>
#include <iterator>
#include <iomanip>

int main()
{
int foo[] = {1, 2, 3, 4};

do
{
std::copy(foo, foo+4, std::ostream_iterator<int>(std::cout, " "));
std::cout << std::endl;
}
while(std::next_permutation(foo, foo+4));
}
[/source]
It assumes that the array is sorted to begin with, since it lists all permutations in lexicographical order and returns false once the last lexicographical order has been passed. For arbitrary arrays, just sort it before listing the permutations. It it is not sorted, you will only get the permutations after (in the lexigographical sense) the initial setup of the array.

##### Share on other sites
I really doubt his instructor is going to allow him to use the std method.

I remember do this very exercise in my first year.

##### Share on other sites

I really doubt his instructor is going to allow him to use the std method.

Which is exactly the reason I gave that answer. If this is a homework, the solution is most likely not allowed and he will have to learn, but I gave him the necessary terms to start searching along with code that demonstrates that it works. If this is not a homework, then it is a valid approach, but it's not about giving an answer to a homework anyway.

1. 1
2. 2
Rutin
16
3. 3
4. 4
5. 5

• 11
• 26
• 10
• 11
• 9
• ### Forum Statistics

• Total Topics
633722
• Total Posts
3013538
×