From 8a69ea8cb7cacf46df7af9bf2686e2a3d44d0b9e Mon Sep 17 00:00:00 2001 From: Aadhavan Srinivasan Date: Wed, 6 Nov 2024 15:13:35 -0500 Subject: [PATCH] Added unique array data structure - O(1) addition and retrieval (I think) --- unique_array.go | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 unique_array.go diff --git a/unique_array.go b/unique_array.go new file mode 100644 index 0000000..d9492d0 --- /dev/null +++ b/unique_array.go @@ -0,0 +1,28 @@ +package main + +// Unique array data structure +type uniq_arr[T comparable] struct { + backingMap map[T]struct{} // Map is used to check if element exists - Empty structs occupy zero memory + vals []T +} + +func new_uniq_arr[T comparable]() uniq_arr[T] { + return uniq_arr[T]{ + make(map[T]struct{}), + make([]T, 0), + } +} +func (s *uniq_arr[T]) add(vals ...T) { + for _, item := range vals { + if !s.contains(item) { + s.backingMap[item] = struct{}{} + s.vals = append(s.vals, item) + } + } + return +} + +func (s *uniq_arr[T]) contains(val T) bool { + _, ok := s.backingMap[val] + return ok +}