Jump to content
  • Advertisement
Sign in to follow this  
Barguast

Get all array arrangements

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

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
Share on other sites
Advertisement
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 this post


Link to post
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 this post


Link to post
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!