Jump to content


- - - - -

Generating all possible combinations


4 replies to this topic

#1 udvat

    Valued Member

  • Members
  • PipPipPip
  • 111 posts

Posted 03 June 2012 - 04:49 PM

Hi,

I want to generate all possible combinations from a set of n numbers and
want to exclude the combinations with hold two consecutive numbers.

For example,

S={1,2,3}

I just want to generate
1;
2;
3;
1,3;

Is there any smart way of doing this other than generating all combinations first and
removing the unwanted ones?

Thanks in advance

#2 Reedbeta

    DevMaster Staff

  • Administrators
  • 5305 posts
  • LocationBellevue, WA

Posted 04 June 2012 - 03:04 AM

To generate all the combinations you'll need nested loops, e.g. for combinations of two you'd have a loop to choose the first number and a loop to choose the second number. Just start the inner loop two later than the outer value rather than one later, and it'll skip the consecutive ones.
reedbeta.com - developer blog, OpenGL demos, and other projects

#3 udvat

    Valued Member

  • Members
  • PipPipPip
  • 111 posts

Posted 04 June 2012 - 08:07 AM

It's not just a combination of two, it can be combination of any size upto n.

#4 geon

    Senior Member

  • Members
  • PipPipPipPip
  • 939 posts

Posted 04 June 2012 - 08:41 AM

Your list of results is not consistent with your description. None of the sequences below have two consecutive digits, I think?

3,1
2,1
2,1,3
2,3,1
1,3,2

Or did you mean something else?

Perhaps you could show us how you would implement it in the naïve way?

#5 Reedbeta

    DevMaster Staff

  • Administrators
  • 5305 posts
  • LocationBellevue, WA

Posted 04 June 2012 - 04:05 PM

View Postudvat, on 04 June 2012 - 08:07 AM, said:

It's not just a combination of two, it can be combination of any size upto n.

The same approach should still work. Generalizing it to size n is left as an exercise for the reader. ;)
reedbeta.com - developer blog, OpenGL demos, and other projects





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users