Delete / delete array elements that form a PHP pair

There are two arrays that say below the data -
$ a = Array (a, b, d, c, e, a); $ b = Array (a, a, d, e, c, a);

I want to delete an instance of array values ​​as a pair, i.e. it must exist in the array 'a' and array 'b' If you understand, I want to remove the elements that form a similar pair.

The result should finally be - $a = [b]; $b = [a];because these are the only remaining elements that do not create a pair.

I tried using array_diff but did not get the expected result -

$arr1 = array_diff($aArr, $bArr);
$arr2 = array_diff($bArr, $aArr);

print_r($arr1);
print "<br>";
print_r($arr2);

$res = count($arr1) + count($arr2);
print $res;

This code works fine when the input signal is Array (c, d, e)
Array (a, b, c)

(a, a, b, d, e, c, a)
(b, a, b, d, e, c, a)

? .

+4
4

array_filter :

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

$a = array_filter($a, function ($element) use (&$b) {
    if (($key = array_search($element, $b)) !== false) {
        unset($b[$key]);

        return false;
    }

    return true;
});

.

array_filter (, true , false ). $b $a . $b , .

+3

.

$arr1 = removePairs($aArr, $bArr);
$arr2 = removePairs($bArr, $aArr);

print_r($arr1);
print "<br>";
print_r($arr2);

$res = count($arr1) + count($arr2);
print $res;

function removePairs($a, $b)
{
    $r = array();

    foreach ($a as $index => $value) {
        $found = array_search($value, $b);

        if ($found !== false) {
            $b[$found] .= '-';
        } else {
            $r[] = $value;
        }
    }

    return $r;
}
0

,

foreach ($a as $aItem){
    if(!in_array($aItem, $b)){
        $arr1[] = $aItem;
    }
}
var_dump($arr1);
0

, . ( ).

$a = ['a', 'b', 'd', 'c', 'e', 'a'];
$b = ['a', 'a', 'd', 'e', 'c', 'a'];
$ha = $hb = [];
foreach ($a as $v) $ha[$v]++;
foreach ($b as $v) $hb[$v]++;

foreach (range('a', 'z') as $l) {
    if (empty($ha[$l])) continue;
    if (empty($hb[$l])) continue;
    if ($ha[$l] > $hb[$l]) {
        $ha[$l] = $ha[$l] - $hb[$l];
        unset($hb[$l]);
        continue;
    }
    $hb[$l] = $hb[$l] - $ha[$l];
    unset($ha[$l]);
}
$a = [];
$b = [];
foreach ($ha as $l => $n) $a = array_merge($a, array_fill(0, $n, $l));
foreach ($hb as $l => $n) $b = array_merge($b, array_fill(0, $n, $l));

var_dump([$a, $b]);

Above the code is O (N), since the accepted answer is O (N ^ 2). Therefore, choose from simplicity or speed.

0
source

Source: https://habr.com/ru/post/1690996/


All Articles