combination.php 的源代码:


<?php
  if ($_POST["left_items"] == "")
  {
    $_POST["left_items"] = "1 2 3";
  }
  if ($_POST["right_items"] == "")
  {
    $_POST["right_items"] = "5 6";
  }

  $left_data = chop (trim ($_POST["left_items"]));
  $left = explode (" ", $left_data);
  sort ($left);
  $left_data = implode (" ", $left);

  $right_data = chop (trim ($_POST["right_items"]));
  $right = explode (" ", $right_data);
  sort ($right);
  $right_data = implode (" ", $right);

  twice_merge($left, 0, $right, 0);
?>

<?php
function twice_merge(&$left, $pl, &$right, $pr)
{
  if (($pl < 0) or ($pl >= count($left))
      or ($pr < 0) or ($pr >= count($right)))
    return;

  $tmp = array();
  for ($i = $pl, $j = $pr; 
       ($i < count($left)) and ($j < count($right));)
    if ($left[$i] < $right[$j])
      $tmp[] = $left[$i++];
    else
      $tmp[] = $right[$j++];

  for (; $i < count($left); ++$i)
    $tmp[] = $left[$i];
  for (; $j < count($right); ++$j)
    $tmp[] = $right[$j];

  $k = 0;
  for ($i = $pl; $i < count($left); ++$i)
    $left[$i] = $tmp[$k++];
  for ($j = $pr; $j < count($right); ++$j)
    $right[$j] = $tmp[$k++];

  return;
}

function nextcombi (&$left, &$right)
{
  if ((count($left) == 0) or (count($right) == 0))
    return true;
  
  $pr = count($right)-1;
  for ($pl = count($left)-1;
       ($pl >= 0) and ($left[$pl] >= $right[$pr]);
       --$pl)
    ;
  
  $ret = $pl >= 0;
  if ($ret)
    {
      for (; ($pr > 0) and ($right[$pr-1] > $left[$pl]); --$pr)
	;
      $t = $left[$pl];
      $left[$pl] = $right[$pr];
      $right[$pr] = $t;
      ++$pl;
      ++$pr;
    }
  else
    {
      $pl = 0;
      $pr = 0;
    }

  twice_merge ($left, $pl, $right, $pr);

  return $ret;
}

?>
<html>
<head>
  <meta HTTP-EQUIV="content-type" CONTENT="text/html; charset=UTF-8">
  <title>Combination Algorithm</title>
</head>
<body>
  <form action="combination.php" method="post">
  <table>
    <tr>
      <td><input type="text" name="left_items" value="<? echo $left_data; ?>"></td>
      <td><input type="text" name="right_items" value="<? echo $right_data; ?>"></td>
      <td><input type="submit" value="Generate Combinations"></td>
    </tr>
  </table>
  </form>

  <table width="60%">
    <tr>
      <th width="50" bgcolor="yellow">Order</th>
      <th bgcolor="EEEEFF">the Combination</th>
      <th bgcolor="EEFFEE">Unselected Elements</th>
    </tr>
<?php
  $num = 1;

  do
  {
?>
    <tr>
      <td align="center"><? echo $num; ?> </td>
      <td><? echo implode(" ", $left); ?></td>
      <td>[<? echo implode(" ", $right); ?>]</td>
    </tr>
<?php
    $num++;
  }
  while (($num < 5000) and nextcombi($left, $right));
?>
  </table>
</body>
</html>