views:

77

answers:

3

Here is the function description

test($argv)

$argv is an array, for example $argv=array($from1,$to1,$from2,$to2.....); array items must be even.

$argv=array(1,3,4,5) : this will output values like below:

1_4
1_5
2_4
2_5
3_4
3_5

pseudocode is like

while($from1<=$to1){
   while($from2<=$to2){
         echo $from1."_".$from2."<br/>";
        $from2++;
   }
   $from1++;
}

$argv=array(1,2,3,4,5,6) : this will output values like below:

1_3_5
1_3_6
1_4_5
1_4_6
2_3_5
2_3_6
2_4_5
2_4_6

pseudocode is like

while($from1<=$to1){
   while($from2<=$to2){
        while($from3<=$to3){
             echo $from1."_".$from2."_".$from3."<br/>";
             $from3++;
        }
        $from2++;
   }
   $from1++;
}

The number of array $argv's is not constant. Maybe 3 or 4 levels of loop will be outputed.

i just heard that tail recuision or iteration will be used, but i don't know exactly how to code.

A: 

Something like this?

test("1", "2", "4", "5", "6", "7", "8", "9");

function test(){
    $args = func_get_args();
    $cnt = func_num_args();
    //echo "cnt :: " . ($cnt % 2) . "\n";

    if(($cnt % 2) > 0) return false;

    $split = $cnt / 2;
    list($list1, $list2) = array_chunk($args, ($cnt / 2));
foreach($list1 as $idx=>$val){
    foreach($list2 as $idx2=>$val2){
        echo $list1[$idx] . "_" . $list2[$idx] . "\n";
    }
}       
}

Here's the output:

1_6
1_6
1_6
1_6
2_7
2_7
2_7
2_7
4_8
4_8
4_8
4_8
5_9
5_9
5_9
5_9
silent
@silent no,not like this,dude.recursive must be used to output what i need.
tunpishuang
@tunpishuang Why do you insist on recursion? The best you could do here is tail recursion, which is the same as a loop.
deceze
oops, didn't see the updated question
silent
I think this is from school task.
silent
@slient yeah,that's right,i am a newbie in programming php.
tunpishuang
+1  A: 
RC
No more OK with edited question..
RC
+1  A: 

The below function should do what you want. It doesn't print the result but instead returns an array with the results that you can iterate over and print it.

$testArray = array('1', '3', '4', '5');
$testArray2 = array('1', '2', '3', '4', '5', '6');

function test($a) {
  $from1 = array_shift($a);
  $to1 = array_shift($a);

  $result = array();

  while ($from1 <= $to1) {
    if (sizeof($a) > 0) {
      $rest = test($a);
      foreach ($rest as $b) {
        $result[] = $from1.'_'.$b;
      }

    } else {
      $result[] = $from1;
    }
    $from1++;
  }
  return $result;
}

print_r(test($testArray));
print_r(test($testArray2));

As an advice read up on recursion as it's an extremely useful technique. It's sometimes hard to wrap your head around it but it's well worth the effort. This book from MIT has a great chapter on recursion if i remember correctly, and its free. Have fun.

jondro
This answer is totaly wrong. LOL
jondro
fixed it to do the proper thing (I hope).
jondro
@jondro thx, u solved it.
tunpishuang