Share occurrence duplicate grouping bookkeeping

This commit is contained in:
2026-11-26 02:53:03 +00:00
parent 6275c62d25
commit f9dd53f4c2
9 changed files with 180 additions and 66 deletions

View File

@@ -0,0 +1,37 @@
package shared
// DuplicatePositions identifies a retained representative and later duplicates
// by their positions in the caller's input sequence.
type DuplicatePositions struct {
Representative int
Removed []int
}
// GroupDuplicates retains the first eligible record per key; ineligible records
// remain independent. Duplicate groups follow representative encounter order.
func GroupDuplicates[K comparable](count int, keyFor func(int) (K, bool)) ([]int, []DuplicatePositions) {
retained := make([]int, 0, count)
groups := make([]DuplicatePositions, 0)
byKey := make(map[K]int)
for index := 0; index < count; index++ {
key, eligible := keyFor(index)
if !eligible {
retained = append(retained, index)
continue
}
if group, exists := byKey[key]; exists {
groups[group].Removed = append(groups[group].Removed, index)
continue
}
byKey[key] = len(groups)
groups = append(groups, DuplicatePositions{Representative: index})
retained = append(retained, index)
}
var duplicates []DuplicatePositions
for _, group := range groups {
if len(group.Removed) > 0 {
duplicates = append(duplicates, group)
}
}
return retained, duplicates
}

View File

@@ -0,0 +1,21 @@
package shared
import (
"reflect"
"testing"
)
func TestGroupDuplicatesKeepsIneligibleAndRepresentativeOrder(t *testing.T) {
keys := []string{"a", "b", "invalid", "b", "invalid", "a", "c"}
retained, groups := GroupDuplicates(len(keys), func(index int) (string, bool) { return keys[index], keys[index] != "invalid" })
if want := []int{0, 1, 2, 4, 6}; !reflect.DeepEqual(retained, want) {
t.Fatalf("retained = %v, want %v", retained, want)
}
if want := []DuplicatePositions{{Representative: 0, Removed: []int{5}}, {Representative: 1, Removed: []int{3}}}; !reflect.DeepEqual(groups, want) {
t.Fatalf("groups = %#v, want %#v", groups, want)
}
retained, groups = GroupDuplicates(0, func(int) (string, bool) { t.Fatal("unexpected callback"); return "", false })
if retained == nil || len(retained) != 0 || len(groups) != 0 {
t.Fatalf("empty result = %#v, %#v", retained, groups)
}
}