mirror of
https://github.com/duke-git/lancet.git
synced 2026-02-04 12:52:28 +08:00
feat: add Difference and SymmetricDifference for list
This commit is contained in:
@@ -5,8 +5,9 @@
|
||||
package datastructure
|
||||
|
||||
import (
|
||||
"github.com/duke-git/lancet/v2/iterator"
|
||||
"reflect"
|
||||
|
||||
"github.com/duke-git/lancet/v2/iterator"
|
||||
)
|
||||
|
||||
// List is a linear table, implemented with slice.
|
||||
@@ -317,6 +318,43 @@ func (l *List[T]) Intersection(other *List[T]) *List[T] {
|
||||
return result
|
||||
}
|
||||
|
||||
// Difference returns the difference between two collections.
|
||||
// return a list whose element in the original list, not in the given list.
|
||||
func (l *List[T]) Difference(other *List[T]) *List[T] {
|
||||
result := NewList(make([]T, 0))
|
||||
|
||||
intersectList := l.Intersection(other)
|
||||
|
||||
for _, v := range l.data {
|
||||
if !intersectList.Contain(v) {
|
||||
result.data = append(result.data, v)
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// SymmetricDifference oppoiste operation of intersection function.
|
||||
func (l *List[T]) SymmetricDifference(other *List[T]) *List[T] {
|
||||
result := NewList(make([]T, 0))
|
||||
|
||||
intersectList := l.Intersection(other)
|
||||
|
||||
for _, v := range l.data {
|
||||
if !intersectList.Contain(v) {
|
||||
result.data = append(result.data, v)
|
||||
}
|
||||
}
|
||||
|
||||
for _, v := range other.data {
|
||||
if !intersectList.Contain(v) {
|
||||
result.data = append(result.data, v)
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// SubList returns a sub list of the original list between the specified fromIndex, inclusive, and toIndex, exclusive.
|
||||
func (l *List[T]) SubList(fromIndex, toIndex int) *List[T] {
|
||||
data := l.data[fromIndex:toIndex]
|
||||
|
||||
@@ -328,6 +328,28 @@ func TestIntersection(t *testing.T) {
|
||||
assert.Equal(true, expected.Equal(list3))
|
||||
}
|
||||
|
||||
func TestDifference(t *testing.T) {
|
||||
assert := internal.NewAssert(t, "TestDifference")
|
||||
|
||||
list1 := NewList([]int{1, 2, 3})
|
||||
list2 := NewList([]int{1, 2, 4})
|
||||
expected := NewList([]int{3})
|
||||
|
||||
list3 := list1.Difference(list2)
|
||||
assert.Equal(true, expected.Equal(list3))
|
||||
}
|
||||
|
||||
func TestSymmetricDifference(t *testing.T) {
|
||||
assert := internal.NewAssert(t, "TestSymmetricDifference")
|
||||
|
||||
list1 := NewList([]int{1, 2, 3})
|
||||
list2 := NewList([]int{1, 2, 4})
|
||||
expected := NewList([]int{3, 4})
|
||||
|
||||
list3 := list1.SymmetricDifference(list2)
|
||||
assert.Equal(true, expected.Equal(list3))
|
||||
}
|
||||
|
||||
func TestSubSlice(t *testing.T) {
|
||||
assert := internal.NewAssert(t, "TestSubSlice")
|
||||
|
||||
|
||||
Reference in New Issue
Block a user