Here is the excise:
You start with an empty room and a group of n people waiting outside. At each step, you may either admit one person into the room, or let one out. Can you arrange a sequence of 2n steps, so that every possible combination of people is achieved exactly once?
My solution is:
I can have a bit array which has n elements. Each element’s status stands for whether this person is in the room or not. So totally we will have 2n different combinations of people in the room.
The algorithm can be a standard backtrack to list out all the combinations.
I am just wondering whether my thought is too naive or simple?
Any trap in this excise?
Edit:
For people who are interested in the implementation of gray code, please see
Your solution “works”, but if implemented naively, it will requires a lot more than 2n steps.
See the following sentence in the problem statement:
In your solution, when you list all bit-vectors, you’ll probably have
0111followed by1000which means that three people will have to leave the room, and one person will have to enter.That requires 4 steps, and not one, thus you’ll get a lot more than 2n steps to run through all combinations.
However, you can arrange the bit-vectors you describe, in a way such that only one bit differs between two consecutive vectors. This is what is refered to as Gray code.
Here’s an example from the Wikipedia article:
Notice how
This means that you’ll be able to iterate through all combinations in precisely 2n steps.
How to implement such sequence generator is also explained in the Wikipedia page, but if it’s an exercise, I suggest you make an attempt yourself before peeking 😉