Skip to content

Instantly share code, notes, and snippets.

@iolloyd
Last active December 31, 2015 15:19
Show Gist options
  • Save iolloyd/69974d421b16963b644d to your computer and use it in GitHub Desktop.
Save iolloyd/69974d421b16963b644d to your computer and use it in GitHub Desktop.
non-recursive method to diff sorted sets of ints
<?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