note 59113 added to control-structures.for

From: Date: Sat, 26 Nov 2005 14:29:46 +0000
Subject: note 59113 added to control-structures.for
Groups: php.notes 
Request: Send a blank email to php-notes+get-99149@lists.php.net to get a copy of this message
Here a bit more flexible solution of a task "brutforce" by "jdtoth -at- gmail dot com", and also should be faster ;-) It uses recursion. But it requires quite much memory (especially when playing with $num_positions), I'm not sure it's OK... If anybody has ideas about that - you are welcome: ultraBoy aat mail ddot ru <?php function get_result($len, &$alphabet) { if ($len == 1) { $result = array(); while (list($row_key, $row) = each($alphabet)) { $result[] = array($row); }; } else { $result = get_result($len - 1, $alphabet); reset($result); $new_result = array(); while (list($row_key, $row) = each($result)) { reset($alphabet); while (list($l_key, $l) = each($alphabet)) { $new_row = $row; $new_row[] = $l; $new_result[] = $new_row; }; } $result = $new_result; } return $result; } // suspected combination numbers $numbers = array(12,18,24,36); // how many numbers are in one combunation $num_positions = 3; echo 'Total rows: '.pow(count($numbers), $num_positions).'<br />'; $result = get_result($num_positions, $numbers); foreach ($result as $row_num => $row) { echo "$row_num: "; foreach ($row as $val) { echo $val.' '; } echo '<br />'; } ?> ---- Manual Page -- http://www.php.net/manual/en/control-structures.for.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+59113 Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+59113&report=yes&reason=added+to+the+manual Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+59113&report=yes&reason=bad+code Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+59113&report=yes&reason=spam Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+59113&report=yes&reason=useless Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+59113&report=yes&reason=non-english Delete: already in docs -- http://master.php.net/manage/user-notes.php?action=delete+59113&report=yes&reason=already+in+docs Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+59113&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+59113&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#99149) next »