Intersect returns a slice of values that are present in all of the input slices example #1 a := []int{1, 1, 3, 4, 5, 6} b := []int{2, 3, 6} fmt.Println(Intersect[int](a, b)) output: []int{3, 6} example #2 fmt.Println(Intersect[int]([]int{1, 1, 3, 4, 5, 6})) output: []int{1, 3, 4, 5, 6}
(arrs ...[]T)
| 120 | // fmt.Println(Intersect[int]([]int{1, 1, 3, 4, 5, 6})) |
| 121 | // // output: []int{1, 3, 4, 5, 6} |
| 122 | func Intersect[T comparable](arrs ...[]T) []T { |
| 123 | m := make(map[T]int) |
| 124 | |
| 125 | var ( |
| 126 | tmpArr []T |
| 127 | count int |
| 128 | ok bool |
| 129 | ) |
| 130 | for idx1 := range arrs { |
| 131 | tmpArr = Distinct(arrs[idx1]) |
| 132 | |
| 133 | for idx2 := range tmpArr { |
| 134 | count, ok = m[tmpArr[idx2]] |
| 135 | if !ok { |
| 136 | m[tmpArr[idx2]] = 1 |
| 137 | } else { |
| 138 | m[tmpArr[idx2]] = count + 1 |
| 139 | } |
| 140 | } |
| 141 | } |
| 142 | |
| 143 | var ( |
| 144 | ret []T |
| 145 | lenArrs int = len(arrs) |
| 146 | ) |
| 147 | for k, v := range m { |
| 148 | if v == lenArrs { |
| 149 | ret = append(ret, k) |
| 150 | } |
| 151 | } |
| 152 | |
| 153 | return ret |
| 154 | } |
| 155 | |
| 156 | // Union returns a slice that contains the unique values of all the input slices |
| 157 | // |
searching dependent graphs…