Debian Codegraph @

exslices/diff.go

raw
1 // Copyright (c) 2023 Tulir Asokan
2 //
3 // This Source Code Form is subject to the terms of the Mozilla Public
4 // License, v. 2.0. If a copy of the MPL was not distributed with this
5 // file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
7 package exslices
8
9 // SortedDiff returns the difference between two already-sorted slices, with the help of the given comparison function.
10 // The output will be in the same order as the input, which means it'll be sorted.
11 func SortedDiff[T any](a, b []T, compare func(a, b T) int) (uniqueToA, uniqueToB []T) {
12 uniqueToA = make([]T, 0, len(a))
13 uniqueToB = make([]T, 0, len(b))
14
15 var i, j int
16 for {
17 if j >= len(b) {
18 uniqueToA = append(uniqueToA, a[i:]...)
19 break
20 } else if i >= len(a) {
21 uniqueToB = append(uniqueToB, b[j:]...)
22 break
23 }
24 c := compare(a[i], b[j])
25 if c < 0 {
26 uniqueToA = append(uniqueToA, a[i])
27 i++
28 } else if c > 0 {
29 uniqueToB = append(uniqueToB, b[j])
30 j++
31 } else {
32 i++
33 j++
34 }
35 }
36 return
37 }
38
39 // Diff returns the difference between two slices. The slices may contain duplicates and don't need to be sorted.
40 // The output will not be sorted, but is guaranteed to not contain any duplicates.
41 func Diff[T comparable](a, b []T) (uniqueToA, uniqueToB []T) {
42 maxLen := len(a)
43 if len(b) > maxLen {
44 maxLen = len(b)
45 }
46 collector := make(map[T]uint8, maxLen)
47 for _, item := range a {
48 collector[item] |= 0b01
49 }
50 for _, item := range b {
51 collector[item] |= 0b10
52 }
53 uniqueToA = make([]T, 0, maxLen)
54 uniqueToB = make([]T, 0, maxLen)
55 for item, mask := range collector {
56 if mask == 0b01 {
57 uniqueToA = append(uniqueToA, item)
58 } else if mask == 0b10 {
59 uniqueToB = append(uniqueToB, item)
60 }
61 }
62 return
63 }