From c169cf3b3e1faa13a1f057da56876c32cb1ebc1f Mon Sep 17 00:00:00 2001 From: emahiro Date: Sat, 22 Apr 2023 23:16:32 +0900 Subject: [PATCH] fix: add test --- leetcode-study/leetcode-26/go.mod | 5 +++ leetcode-study/leetcode-26/go.sum | 2 + leetcode-study/leetcode-26/main.go | 5 +++ leetcode-study/leetcode-26/main_test.go | 60 +++++++++++++++++++++++++ 4 files changed, 72 insertions(+) create mode 100644 leetcode-study/leetcode-26/go.mod create mode 100644 leetcode-study/leetcode-26/go.sum create mode 100644 leetcode-study/leetcode-26/main.go create mode 100644 leetcode-study/leetcode-26/main_test.go diff --git a/leetcode-study/leetcode-26/go.mod b/leetcode-study/leetcode-26/go.mod new file mode 100644 index 0000000..b7a8f6f --- /dev/null +++ b/leetcode-study/leetcode-26/go.mod @@ -0,0 +1,5 @@ +module github.com/emahiro/il/leetcode-26 + +go 1.20 + +require golang.org/x/exp v0.0.0-20230420155640-133eef4313cb diff --git a/leetcode-study/leetcode-26/go.sum b/leetcode-study/leetcode-26/go.sum new file mode 100644 index 0000000..6b0eb31 --- /dev/null +++ b/leetcode-study/leetcode-26/go.sum @@ -0,0 +1,2 @@ +golang.org/x/exp v0.0.0-20230420155640-133eef4313cb h1:rhjz/8Mbfa8xROFiH+MQphmAmgqRM0bOMnytznhWEXk= +golang.org/x/exp v0.0.0-20230420155640-133eef4313cb/go.mod h1:V1LtkGg67GoY2N1AnLN78QLrzxkLyJw7RJb1gzOOz9w= diff --git a/leetcode-study/leetcode-26/main.go b/leetcode-study/leetcode-26/main.go new file mode 100644 index 0000000..36c7149 --- /dev/null +++ b/leetcode-study/leetcode-26/main.go @@ -0,0 +1,5 @@ +package main + +import "fmt" + +func main() { fmt.Println("hello world") } diff --git a/leetcode-study/leetcode-26/main_test.go b/leetcode-study/leetcode-26/main_test.go new file mode 100644 index 0000000..df7c2a6 --- /dev/null +++ b/leetcode-study/leetcode-26/main_test.go @@ -0,0 +1,60 @@ +package main + +import ( + "testing" + + "golang.org/x/exp/slices" +) + +func uniqNormal(s *[]int) { + m := make(map[int]struct{}) + for _, v := range *s { + m[v] = struct{}{} + } + *s = (*s)[:0] + for k := range m { + *s = append(*s, k) + } +} + +func uniqFast(s *[]int) { + offset := 1 + for i := 1; i < len(*s); i++ { + if (*s)[i] != (*s)[i-1] { + (*s)[offset] = (*s)[i] + offset++ + } + } + *s = (*s)[:offset] +} + +func uniqGen[T comparable](s *[]T) { + _ = slices.Compact(*s) +} + +func Benchmark(b *testing.B) { + b.ReportAllocs() + + list := []int{1, 1, 2, 2} + + b.Run("unique normal", func(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + uniqNormal(&list) + } + }) + + b.Run("unique faster", func(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + uniqFast(&list) + } + }) + + b.Run("unique generic", func(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + uniqGen(&list) + } + }) +}