【问题标题】:Combine neighbouring elemets to new array of min 2将相邻元素组合成最小 2 的新数组
【发布时间】:2021-07-28 18:40:05
【问题描述】:

我有一个非常具体的问题。我想将数组的每个元素与相邻元素组合成一个最小长度为 2 的新数组。我不确定我是否正确解释,所以这里有一个例子:

给定数组:

$array = ['a', 'b', 'c', 'd'];

我想创建一个如下所示的新数组:

[
  ['ab', 'c', 'd'],
  ['ab', 'cd'],
  ['abc', 'd'],
  ['a', 'bc', 'd'],
  ['a', 'bcd'],
  ['a', 'b', 'cd']
]

['abcd'] 没有返回,因为它的长度只有 1。

【问题讨论】:

    标签: php arrays for-loop


    【解决方案1】:

    我想我会发布一个答案,因为我得到了其他人的帮助。

    function permutations($array, $i)
    {
        if($i >= count($array) - 1)
        {
            return array($array);
        }
    
        $newArray = $array;
        $newArray[$i] .= $newArray[$i + 1];
    
        unset($newArray[$i+1]);
    
        $newArray = array_values($newArray);
    
        $a = permutations($newArray, $i );
    
        $b = permutations( $array, $i + 1);
    
        return array_merge($a, $b);
    }
    
    //$array = ['a', 'b', 'c', 'd'];
    
    //print_r(permutations($array, 0));
    

    【讨论】:

      猜你喜欢
      • 2017-12-05
      • 2021-12-25
      • 1970-01-01
      • 2018-04-23
      • 1970-01-01
      • 1970-01-01
      • 2019-12-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多