StrSlice substraction.

This commit is contained in:
Andrey Smirnov
2014-02-12 12:59:02 +04:00
parent 8ae1f7aab0
commit 974d30b837
2 changed files with 53 additions and 0 deletions
+37
View File
@@ -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
}
+16
View File
@@ -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)
}