Please help: combining elements of an array
| From: | Scott S. Nicholson | Date: | Fri, 28 Jul 2000 03:51:18 +0000 |
| Subject: | Please help: combining elements of an array | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-8708@lists.php.net to get a copy of this message | ||
Greetings,
I've been banging my head against a wall trying to figure out how to do
this...
I've got an array that could contain any number of elements. I want to
combine those elements in all possible ways (without repeating the same
element in any given combination).
For example:
$list = array("A", "B", "C", "D");
$combo = combine($list); /* (This is the function I need help creating)
*/
After running this script, $combo would contain the following elements
(though I don't really care if they're in this order or not):
A B C D AB AC AD BA BC BD CA CB CD DA DB DC ABC ABD ACB ACD ADB ADC BAC BAD
BCA BCD BDA BDC CAB CAD CBA CBD CDA CDB DAB DAC DBA DBC DCA DCB ABCD ABDC
ACBD ACDB ADBC ADCB BACD BADC BCAD BCDA BDAC BDCA CABD CADB CBAD CBDA CDAB
CDBA DABC DACB DBAC DBCA DCAB DCBA
Notice that no elements contain the same letter more than once. This makes
things a little more complicated, as in the real application the original
elements may not be just letters, but words (and though preventing duplicate
letters would be fairly simple, preventing duplicate words will be a bit
harder, esp. if the list includes words such as 'the' and 'other').
For extra credit, allow me to specify a lower and upper limit on the number
of terms that will be combined (i.e. if I specify limits of 2 and 3 the
single letters and the four-letter combinations will be excluded.)
Remember that the array could contain as few as one and as many as ??
elements.
I'm sure I need some sort of recursive algorithm (i.e. the function calls
itself), but I've never been too good at those, which is why I'm asking for
help.
Any ideas? (please reply directly to me as well as to the list, as I read
the list through news.php.net and occasionally miss posts)
TIA
Scott Nicholson
scottn@pnx1.com