Last active
December 31, 2015 15:19
-
-
Save iolloyd/69974d421b16963b644d to your computer and use it in GitHub Desktop.
non-recursive method to diff sorted sets of ints
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 tail(array $a) | |
{ | |
$out = []; | |
unset($a[0]); | |
foreach ($a as $v) { | |
$out[] = $v; | |
} | |
return $out; | |
} | |
// Non recursive version of previous method | |
function setDiff($a, $b) | |
{ | |
$out = []; | |
while ($a != [] && $b != []) { | |
$headA = $a[0]; | |
$headB = $b[0]; | |
if ($headA == $headB) { | |
$a = tail($a); | |
$b = tail($b); | |
} else if ($headA < $headB) { | |
$out[] = $headA; | |
$a = tail($a); | |
} else if ($headA > $headB) { | |
$b = tail($b); | |
} | |
} | |
return array_merge($out, $a); | |
} | |
$listB = [2, 5, 9, 10, 12, 14]; | |
$listA = [1, 2, 3, 8, 9]; | |
/* | |
A = 1 2 3 8 9 | |
B = 2 5 9 10 12 14 | |
{A - B} = 1 3 8 | |
{B - A} = 5 10 12 14 | |
*/ | |
var_dump(assert([1, 3, 8] == setDiff($listA, $listB))); | |
var_dump(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