Skip to content

Instantly share code, notes, and snippets.

@iolloyd
Last active December 31, 2015 13:39
Show Gist options
  • Save iolloyd/24cde87f590a0ad18b54 to your computer and use it in GitHub Desktop.
Save iolloyd/24cde87f590a0ad18b54 to your computer and use it in GitHub Desktop.
set differences order dependant
<<?php
function setDiff($a, $b, $out=[])
{
if ($a == [] || $b == []) {
foreach ($a as $v) {
$out[] = $v;
}
return $out;
}
$headA = $a[0];
$headB = $b[0];
if ($headA == $headB) {
return setDiff(tail($a), tail($b), $out);
}
if ($headA < $headB) {
$out[] = $headA;
return setDiff(tail($a), $b, $out);
}
return setDiff($a, tail($b), $out);
}
function tail(array $a)
{
$out = [];
unset($a[0]);
foreach ($a as $v) {
$out[] = $v;
}
return $out;
}
$listA = [1, 2, 3, 8, 9];
$listB = [2, 5, 9, 10, 12, 14];
assert([1, 3, 8] == setDiff($listA, $listB));
assert([5, 10, 12, 14] == setDiff($listB, $listA));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment