使用以下条件从数组创建唯一的 3 位数字组合的 PHP 代码

标签 php arrays

条件:

  1. Starting digit should not be 0
  2. Succeeding digits should be greater than preceding numbers.
  3. The last digit can be 0
  4. The middle digit should not be 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++;
  }

 }
}
?>

最佳答案

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

  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>';
}

关于使用以下条件从数组创建唯一的 3 位数字组合的 PHP 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49068979/

相关文章:

Javascript如何找到数组中最大的数字并记录位置

javascript - 如何使用 Javascript 向数组的每一行添加一个字段?

arrays - Racket 中的数组操作 : error "expected indexes for shape ' (6); given '#(6)"

php - Laravel 5 Socialite Facebook 登录用户取消应用程序请求后回调处理错误

php - 使用 PHP PDO 插入多个数组

php - 3 列布局,带有从 mysql 获取数组构建的 div

javascript - 执行数组深处的函数

php - 多维数组 - 搜索值并获取子数组

php - 如何更新字段以将值推送到 Laravel 中的现有值

java - 将 json 数据写入和读取到内部存储 android