PHP代码,用于根据以下条件从数组创建唯一的3位数组合

问题描述 投票:3回答:1

条件:

  1. 起始位数不应为0
  2. 成功的数字应该大于前面的数字。
  3. 最后一位数字可以是0
  4. 中间数字不应为0

我们已经成功地满足了前两个条件,但由于第二个和第三个条件之间的矛盾,我无法获得预期的输出。

例如,输入1234给出输出:

123
124
134
234 

对于数字12340,输出应为:

123
124
134
234
120
120
140
230
240
340

但它与我所做的并不一致。

代码:

<?
function pc_permute($items, $perms = array( )) {
    if (empty($items)) {
        $return = array($perms);
    }  else {
        $return = array();
        for ($i = count($items) - 1; $i >= 0; --$i) {
             $newitems = $items;
             $newperms = $perms;
         list($foo) = array_splice($newitems, $i, 1);
             array_unshift($newperms, $foo);
             $return = array_merge($return, pc_permute($newitems, $newperms));
         }
    }
    return $return;
}

// example
$chars = array('1', '2', '3','4','0');
$output = pc_permute($chars);
$a=count($output);
for ($i = 0; $i<count($output);$i++) {
  for ($j = 0; $j < 3;$j++){
   $c[$i] = $c[$i].$output[$i][$j];
 }
}
$arr = array_unique($c);
$last = end(array_keys($arr));
$n=0;
for($i = 0;$i <= $last;$i++) {
  if(!empty($arr[$i])){
  $temp = $arr[$i];
  $d = str_split($temp);
  $e = end(array_keys($d));
  $flag = 0;
  for($j = 0;$j < (count($d)-1); $j++) {
  if(($d[$j] < $d[$j+1] && $d[0] != 0)) {
   $flag = 1; 
  }
  else {
   $flag = 0;
   break;
  } 
 }
 if($flag == 1) {
   echo $temp;
   echo "<br>";
   $n++;
  }

 }
}
?>
php arrays
1个回答
2
投票

您应该根据规则为您的程序设置以下步骤:

  1. 根据规则2,您可以删除重复项
  2. 由于规则2,您可以对输入进行排序
  3. 由于规则1,3和4,您可以将0移动到数组的末尾(如果存在)

如果这一点得到尊重,你可以使用三个foreach循环遍历输入数组,这些循环使用前面的循环替换后续数字。因为它按正确的顺序排序,所以将自动遵守所有规则。

这些评论解释了每一步所做的工作。

$input = [0, 3, 1, 2, 2, 4];
$results = [];

//Remove duplicates, necessary for rule 2
$input = array_unique($input);  

//Sort Numbers, necessary for rule 2
sort($input);  

// Mark 0 as the greates number, so it can only appear at the end. Necessary for rule 1, 3 and 4
if ($input[0] === 0) {
    $input[] = array_shift($input);
}

$inputCount = count($input);
for( $i = 0; $i < $inputCount - 2; $i++) {
    for ($j = $i + 1; $j < $inputCount - 1; $j++) {
        for ($k = $j + 1; $k < $inputCount; $k++) {
            $results[] = $input[$i] . $input[$j] . $input[$k];
        }
    }
}

foreach ($results as $result) {
    echo $result . '<br>';
}
© www.soinside.com 2019 - 2024. All rights reserved.