Skip to content

Commit f328c5e

Browse files
committed
feat:slice Intersection
1 parent 8976099 commit f328c5e

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

slice/intersection.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package slice
2+
3+
// Intersection
4+
// Creates an array of unique values that are included in all given arrays. The order and references of result values are determined by the first array.
5+
func Intersection[T comparable](arrays [][]T) (result []T) {
6+
if len(arrays) < 2 {
7+
return
8+
}
9+
result = arrays[0]
10+
for i := 1; i < len(arrays); i++ {
11+
result = intersection(result, arrays[i])
12+
if len(result) == 0 {
13+
break
14+
}
15+
}
16+
return
17+
}
18+
19+
func intersection[T comparable](arr1 []T, arr2 []T) (result []T) {
20+
result = []T{}
21+
for i := 0; i < len(arr1); i++ {
22+
if IndexOf(arr2, arr1[i], 0) >= 0 {
23+
result = append(result, arr1[i])
24+
}
25+
}
26+
return
27+
}

slice/intersection_test.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package slice
2+
3+
import "fmt"
4+
5+
func ExampleIntersection() {
6+
arrays := [][]int{
7+
{1, 2, 3, 4, 5, 6},
8+
{5, 4, 2},
9+
{3, 2, 1, 5},
10+
}
11+
12+
fmt.Println(Intersection(arrays))
13+
//Output:
14+
//[2 5]
15+
}

0 commit comments

Comments
 (0)