Last active
December 31, 2015 13:39
-
-
Save iolloyd/24cde87f590a0ad18b54 to your computer and use it in GitHub Desktop.
set differences order dependant
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<<?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