如何有效地合并并可能卷积两个数组?

时间:2022-10-31 12:14:47

Suppose, that I have 3 arrays:

假设我有3个数组:

$a = [ 1, 2, 3 ];       // victim #1
$b = [ 4, 5, 6, 7, 8];  // victim #2
$result = [];           // result

I need to merge $a and $b in such order, that each element of $a array should be followed by element of array $b. Elements of $b array, however, might follow each other.

我需要以这样的顺序合并$ a和$ b,$ a数组的每个元素都应该跟在数组$ b的元素之后。但是,$ b数组的元素可能会相互跟随。

For example:

1 4 2 5 6 3 7 8

I have tried this:

我试过这个:

while($a || $b)
    {
        $bool = rand(1, 100) >= 50;

        if($a)
            {
                $result[] = array_shift($a);
            }

        if($b)
            {
                $result[] = array_shift($b);
            }

        if($bool && $b)
            {
                $result[] = array_shift($b);
            }
    }

Which gives desired output:

这给出了所需的输出:

Array
(
    [0] => 1
    [1] => 4
    [2] => 5
    [3] => 2
    [4] => 6
    [5] => 7
    [6] => 3
    [7] => 8
)

However, I think that it might be inefficient because of array_shift()s and if()s appears too much times there.

但是,我认为由于array_shift()和if()s在那里出现的次数太多,它可能效率低下。

Question: Is there more efficient way to do that?

问题:有更有效的方法吗?

P.S.: Thanks, but I do really know how to use array_merge(). It is not the RTM issue.

P.S。:谢谢,但我确实知道如何使用array_merge()。这不是RTM问题。

2 个解决方案

#1


1  

foreach ($a as $value) {
    $result[] = $value;
    do {
        $bool = rand(0,1) == 1;
        $result[] = array_shift($b);
    } while ($bool);
}
// insert the remaining of value $b in the $result
foreach ($b as $value)
    $result[] = $value;

#2


1  

$a = array(1, 2, 3 );       // victim #1
$b = array( 4, 5, 6, 7, 8);  // victim #2


foreach($a as $first)
{
   $result[] = $first;
}

foreach($b as $second)
{
   $result[] = $second;
}

Alternatively

$a = array(1, 2, 3, 9 );       // victim #1
$b = array( 4, 5, 6, 7, 8);  // victim #2
$result = array_merge($a,$b);

#1


1  

foreach ($a as $value) {
    $result[] = $value;
    do {
        $bool = rand(0,1) == 1;
        $result[] = array_shift($b);
    } while ($bool);
}
// insert the remaining of value $b in the $result
foreach ($b as $value)
    $result[] = $value;

#2


1  

$a = array(1, 2, 3 );       // victim #1
$b = array( 4, 5, 6, 7, 8);  // victim #2


foreach($a as $first)
{
   $result[] = $first;
}

foreach($b as $second)
{
   $result[] = $second;
}

Alternatively

$a = array(1, 2, 3, 9 );       // victim #1
$b = array( 4, 5, 6, 7, 8);  // victim #2
$result = array_merge($a,$b);