Re: Please help: combining elements of an array

From: Date: Fri, 28 Jul 2000 14:09:30 +0000
Subject: Re: Please help: combining elements of an array
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-8783@lists.php.net to get a copy of this message
scottn@pnx1.com ("Scott S. Nicholson") writes: > 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 This works in PHP4: function combine( $list ) { foreach( $list as $item ) { $array_list[] = array($item); } $result = permute($array_list, $max); foreach( $result as $string ) { $retval[] = join("",$string); } return $retval; } function permute ( $list ) { if(sizeof($list)<=1) return $list; $head = array_shift($list); foreach (permute($list) as $string) { for ($i=0; $i <= sizeof( $string ); $i++) { $retval[] = array_merge(array_slice($string,0,$i), $head, array_slice($string,$i)); } $retval[] = $string; } $retval[] = $head; return $retval; } -- Robin Vickery............................................... Planet-Three, 3A West Point, Warple Way, London, W3 0RG, UK Email: robin@planet-three.net Phone: +44 (0)794 670 6395

« previous php.general (#8783) next »