Re: Combinations problem
- From: "Douglas A. Gwyn" <DAGwyn@xxxxxxxx>
- Date: Mon, 4 Apr 2005 18:21:28 GMT
Thomas Cameron wrote:
> I have an array of values which I would like to generate all possible
> combinations for. And example would be the values "a,b,c". This would
> produce the following:
> a
> ab
> abc
> ac
> b
> bc
> c
> Does anybody know of the algorithm to produce this?
I'm pretty sure this must be covered in Knuth, if not earlier
then in one of the preliminary facsicles for Volume 4.
Anyway, it is easy to figure out. Let's assume that all the
array values are distinct, or if not that you want the
duplicates that will be produced. (Otherwise, first sort
the array then walk it and collapse it down to one instance
each.) Then what you want can be characterized by: sets
such that whether or not each element is present in the set
varies through all possible combinations. That should ring
a bell: presence = 1, absence = 0 => binary integer of width
N where N = # elements. Thus all you have to do is enumerate
the distinct possibilities for an N-bit integer, which can be
done simply by counting, starting at 0. For each value of
the counter, slide a 1-bit past it, ANDing to determine
whether or not the corresponding position denotes the presence
or the absence of that element. If present, output the token;
if absent, do nothing. After the 1-bit has been slid N places,
output a newline and increment the counter. Note that this
will also output the empty string (no element present), which
is a valid combination but which you might want to eliminate
(so start the counter at 1 instead).
.
- Prev by Date: Re: Combinations problem
- Next by Date: Re: Combinations problem
- Previous by thread: Re: Combinations problem
- Next by thread: Re: Combinations problem
- Index(es):
Relevant Pages
|