From 974d30b837d95ca7963b3b18d1b1a3fc11f4f008 Mon Sep 17 00:00:00 2001 From: Andrey Smirnov Date: Wed, 12 Feb 2014 12:59:02 +0400 Subject: [PATCH] StrSlice substraction. --- utils/list.go | 37 +++++++++++++++++++++++++++++++++++++ utils/list_test.go | 16 ++++++++++++++++ 2 files changed, 53 insertions(+) diff --git a/utils/list.go b/utils/list.go index 602c07df..40cbe5cd 100644 --- a/utils/list.go +++ b/utils/list.go @@ -101,3 +101,40 @@ func StrSliceDeduplicate(s []string) []string { return s[:j] } + +// StrSlicesSubstract finds all the strings which are in l but not in r, both slices shoult be sorted +func StrSlicesSubstract(l, r []string) []string { + result := make([]string, 0) + + // pointer to left and right reflists + il, ir := 0, 0 + // length of reflists + ll, lr := len(l), len(r) + + for il < ll || ir < lr { + if il == ll { + // left list exhausted, we got the result + break + } + if ir == lr { + // right list exhausted, append what is left to result + result = append(result, l[il:]...) + break + } + + if l[il] == r[ir] { + // r contains entry from l, so we skip it + il++ + ir++ + } else if l[il] < r[ir] { + // item il is not in r, append + result = append(result, l[il]) + il++ + } else { + // skip over to next item in r + ir++ + } + } + + return result +} diff --git a/utils/list_test.go b/utils/list_test.go index 9eaad39f..f8165555 100644 --- a/utils/list_test.go +++ b/utils/list_test.go @@ -56,3 +56,19 @@ func (s *ListSuite) TestStrSliceDeduplicate(c *C) { c.Check(StrSliceDeduplicate([]string{"a", "b", "c", "a", "a", "b"}), DeepEquals, []string{"a", "b", "c"}) c.Check(StrSliceDeduplicate([]string{"a", "b", "c", "d", "e", "f"}), DeepEquals, []string{"a", "b", "c", "d", "e", "f"}) } + +func (s *ListSuite) TestStrSlicesSubstract(c *C) { + empty := []string{} + l1 := []string{"r1", "r2", "r3", "r4"} + l2 := []string{"r1", "r3"} + l3 := []string{"r2", "r4"} + l4 := []string{"r4", "r5"} + l5 := []string{"r1", "r2", "r3"} + + c.Check(StrSlicesSubstract(l1, empty), DeepEquals, l1) + c.Check(StrSlicesSubstract(l1, l2), DeepEquals, l3) + c.Check(StrSlicesSubstract(l1, l3), DeepEquals, l2) + c.Check(StrSlicesSubstract(l1, l4), DeepEquals, l5) + c.Check(StrSlicesSubstract(empty, l1), DeepEquals, empty) + c.Check(StrSlicesSubstract(l2, l3), DeepEquals, l2) +}