2

I am seeking for an algorithm which iterates through all k element subsets of an n element set. I do not want to generate all those subset explicitly.

There is an easy algorithm to do this, namely sorting the corresponding bit vectors lexographically and then go from the current subset to the next one.

Nevertheless, I seek for an algorithm which only switches 2 bits in each step. I have read that such a code is a called "gray-code" but I did not found an algorithm for my problem.

Is there a straight forward implementation for this?

mueldgog
  • 383
  • 1
  • 7
  • 1
    Turning an integer into gray-code is trivial, but I'm not sure enough about what you're doing to know whether that's actually the answer. Could you give you an example or something? – harold May 06 '15 at 19:17
  • Well, the requirement is _like_ a gray code, but I don't think it is technically a gray code. Gray codes switch only one bit, and if you took two steps in a gray sequence you might find that two bits switch on, rather than one on and one off, and you wouldn't have the same number of bits set throughout. – sh1 May 06 '15 at 19:20

1 Answers1

1

This isn't going to be a complete answer, but it's also not going to fit in a comment.

The relationship to gray code that you need is the mirroring. Every time gray code sets a new bit, all the bits below it progress backwards from that point on (until that bit is cleared or a bit above that reverses the reversal).

To reproduce this with your lexicographic ordering you need to invert the order in which you iterate through the remaining bits after each swap.

You might be able to implement this as an iterative transformation, taking your regular ordering and repeatedly reversing the order of the remaining bits every time you encounter a transition from 1 to 0.

sh1
  • 4,324
  • 17
  • 30