Sign in to follow this  
johnnyBravo

How to output every combination from string eg 123, 132, 321, etc

Recommended Posts

johnnyBravo    100
Hi I was trying to work out how to find every combination of characters from a string of n size. eg for a string of n=3: 123 132 213 231 312 321 I thought it would be simple, but im a bit stumped on how to implement it,thx

Share this post


Link to post
Share on other sites
Sneftel    1788
That's not known as a "combination", but a "permutation". Google for "permutation algorithm" and you'll turn up quite a bit of stuff.

Share this post


Link to post
Share on other sites
Beer Hunter    712
If you are using C++ and just want a pre-written function, you can use next_permutation from the <algorithm> header.
std::string mystr = "123";
do
{
std::cout << mystr << std::endl;
}
while (std::next_permutation(mystr.begin(), mystr.end()));

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this