This commit is contained in:
fancl 2023-08-22 16:11:34 +08:00
parent 2c5c83578c
commit 2877f751dc
2 changed files with 116 additions and 0 deletions

View File

@ -0,0 +1,43 @@
package arrays
func IndexOf[T comparable](a T, vs []T) int {
for i, v := range vs {
if v == a {
return i
}
}
return -1
}
func Exists[T comparable](a T, vs []T) bool {
return IndexOf(a, vs) > -1
}
func Fill[T any](startIndex int, num uint, value T) map[int]T {
m := make(map[int]T)
var i uint
for i = 0; i < num; i++ {
m[startIndex] = value
startIndex++
}
return m
}
func Reverse[T comparable](s []T) []T {
for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
s[i], s[j] = s[j], s[i]
}
return s
}
func Merge[T comparable](ss ...[]T) []T {
n := 0
for _, v := range ss {
n += len(v)
}
s := make([]T, 0, n)
for _, v := range ss {
s = append(s, v...)
}
return s
}

View File

@ -0,0 +1,73 @@
package arrays
import (
"reflect"
"testing"
)
func TestIndexOf(t *testing.T) {
type args[T comparable] struct {
a T
vs []T
}
type testCase[T comparable] struct {
name string
args args[T]
want int
}
tests := []testCase[string]{
{"exists", args[string]{a: "a", vs: []string{"a", "b"}}, 0},
{"not exists", args[string]{a: "a", vs: []string{"c", "b"}}, -1},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := IndexOf(tt.args.a, tt.args.vs); got != tt.want {
t.Errorf("IndexOf() = %v, want %v", got, tt.want)
}
})
}
}
func TestExists(t *testing.T) {
type args[T comparable] struct {
a T
vs []T
}
type testCase[T comparable] struct {
name string
args args[T]
want bool
}
tests := []testCase[int]{
{"exists", args[int]{a: 1, vs: []int{1, 2}}, true},
{"not exists", args[int]{a: 2, vs: []int{3, 4}}, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := Exists(tt.args.a, tt.args.vs); got != tt.want {
t.Errorf("Exists() = %v, want %v", got, tt.want)
}
})
}
}
func TestReverse(t *testing.T) {
type args[T comparable] struct {
s []T
}
type testCase[T comparable] struct {
name string
args args[T]
want []T
}
tests := []testCase[int]{
{"one", args[int]{s: []int{1, 2, 3}}, []int{3, 2, 1}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := Reverse(tt.args.s); !reflect.DeepEqual(got, tt.want) {
t.Errorf("Reverse() = %v, want %v", got, tt.want)
}
})
}
}