S SmartDocs
系列: Go go 105 行 · 更新于 2026-04-18

array_test.go

Go/part2-dsa/ds/arrayx/array_test.go

package arrayx

import (
	"reflect"
	"testing"
)

func TestSum(t *testing.T) {
	if got := Sum([]int{1, 2, 3, 4}); got != 10 {
		t.Errorf("Sum = %d, want 10", got)
	}
	if got := Sum([]float64{}); got != 0 {
		t.Errorf("Sum empty = %v, want 0", got)
	}
}

func TestMaxMin(t *testing.T) {
	mx, ok := Max([]int{3, 1, 4, 1, 5, 9, 2, 6})
	if !ok || mx != 9 {
		t.Errorf("Max = %d, %v", mx, ok)
	}
	mn, ok := Min([]int{3, 1, 4, 1, 5, 9, 2, 6})
	if !ok || mn != 1 {
		t.Errorf("Min = %d, %v", mn, ok)
	}
	if _, ok := Max([]int{}); ok {
		t.Error("Max of empty should be !ok")
	}
}

func TestReverse(t *testing.T) {
	s := []int{1, 2, 3, 4, 5}
	Reverse(s)
	want := []int{5, 4, 3, 2, 1}
	if !reflect.DeepEqual(s, want) {
		t.Errorf("Reverse = %v, want %v", s, want)
	}

	r := Reversed([]string{"a", "b", "c"})
	if !reflect.DeepEqual(r, []string{"c", "b", "a"}) {
		t.Errorf("Reversed = %v", r)
	}
}

func TestContainsIndexOf(t *testing.T) {
	s := []int{10, 20, 30}
	if !Contains(s, 20) {
		t.Error("expected to contain 20")
	}
	if IndexOf(s, 999) != -1 {
		t.Error("expected -1 for missing")
	}
}

func TestInsertRemove(t *testing.T) {
	s := []int{1, 2, 4, 5}
	got := Insert(s, 2, 3)
	if !reflect.DeepEqual(got, []int{1, 2, 3, 4, 5}) {
		t.Errorf("Insert = %v", got)
	}

	got = Remove([]int{1, 2, 3, 4, 5}, 2)
	if !reflect.DeepEqual(got, []int{1, 2, 4, 5}) {
		t.Errorf("Remove = %v", got)
	}

	u := []int{1, 2, 3, 4, 5}
	u = RemoveUnordered(u, 1)
	if len(u) != 4 || u[1] == 2 {
		t.Errorf("RemoveUnordered did not remove correctly: %v", u)
	}
}

func TestBinarySearch(t *testing.T) {
	s := []int{1, 3, 5, 7, 9, 11}
	if i, ok := BinarySearch(s, 7); !ok || i != 3 {
		t.Errorf("BinarySearch = %d, %v", i, ok)
	}
	if i, ok := BinarySearch(s, 4); ok || i != 2 {
		t.Errorf("BinarySearch missing = %d, %v", i, ok)
	}
}

func TestTwoSumSorted(t *testing.T) {
	s := []int{1, 2, 4, 6, 10}
	i, j, ok := TwoSumSorted(s, 14)
	if !ok || s[i]+s[j] != 14 {
		t.Errorf("TwoSumSorted = %d %d %v", i, j, ok)
	}
	if _, _, ok := TwoSumSorted(s, 999); ok {
		t.Error("expected no pair")
	}
}

func TestRotateLeft(t *testing.T) {
	s := []int{1, 2, 3, 4, 5}
	RotateLeft(s, 2)
	if !reflect.DeepEqual(s, []int{3, 4, 5, 1, 2}) {
		t.Errorf("RotateLeft = %v", s)
	}
	RotateLeft(s, -2) // rotate back
	if !reflect.DeepEqual(s, []int{1, 2, 3, 4, 5}) {
		t.Errorf("RotateLeft back = %v", s)
	}
}

相关文章