Re: algorithm help ?

From: Date: Sat, 30 Dec 2000 13:24:33 +0000
Subject: Re: algorithm help ?
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-32272@lists.php.net to get a copy of this message
I think this code could work for you: // returns array of permutations of array // not quite correct if argument is an empty array function permute($a) { $c = count($a); if ($c < 2) return array($a); for ($i = 0; $i < $c; $i++) { $b = $a; $e = array_splice($b, $i, 1); $b = permute($b); while ($b) { $f = array_shift($b); $r[] = array_merge($e, $f); } } return $r; } // returns all array of all subsets of n elements from array // should only be called with $n <= size of array function subsets_n($a, $n) { if ( $n == 0 ) return array(array()); $l = count($a) - $n + 1; if ($l < 1) return array($a); for ($i = 0; $i < $l; $i++) { $e = array_splice($a, 0, 1); $s = subsets_n($a, $n - 1); while ($s) { $f = array_shift($s); $r[] = array_merge($e, $f); } } return $r; } $data = array(1, 2, 3, 4); $subs = subsets_n($data, 3); while ($subs) { $p = permute(array_shift($subs)); var_dump($p); } These functions are not very well tested, but seems to work, and also preserves keys. In the example above, I first find all possible subsets of 3 elements from 1, 2, 3, 4, and then I find all permutations of each of those. Try to run this script first of all, and make sure you understand what it does, and please check that there are no bugs.... In your case, you should set $data to an array of 19 numbers, and then do $subs = subsets_n($data, 6); while ($subs) { $p = permute(array_shift($subs)); var_dump($p); } On Fri, Dec 29, 2000 at 11:47:08AM +0200, Gianni Ponzi wrote: > ok > > this is what i'd like to do.... > > I'd like to be able to select 19 numbers between 1 and 49 and work out > the permutations / combinations of those numbers in groups of six. > > eg 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19 > > results: > > 1 2 3 4 5 6 > 1 2 3 5 6 7 > 1 2 3 6 7 8 > > > and so on..... Stig

« previous php.general (#32272) next »