1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-13 17:22:27 +08:00

feat: add Difference and SymmetricDifference for list

This commit is contained in:
dudaodong
2023-02-06 10:55:42 +08:00
parent 6a79e322e3
commit 1fe4cdc429
2 changed files with 61 additions and 1 deletions

View File

@@ -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]