MCPcopy Create free account
hub / github.com/TheAlgorithms/Go / TestFenwickTree

Function TestFenwickTree

structure/fenwicktree/fenwicktree_test.go:19–81  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

17}
18
19func TestFenwickTree(t *testing.T) {
20 var fenwickTreeTestData = []struct {
21 description string
22 array []int
23 updates []update
24 queries []query
25 expected []int
26 }{
27 {
28 description: "test empty array",
29 array: []int{},
30 queries: []query{{"point", 1, 1}},
31 expected: []int{0},
32 },
33 {
34 description: "test array with size 5",
35 array: []int{1, 2, 3, 4, 5},
36 queries: []query{{"range", 1, 5}, {"range", 1, 3}, {"range", 3, 5}},
37 expected: []int{15, 6, 12},
38 },
39 {
40 description: "test array with size 5, single index updates and range queries",
41 array: []int{1, 2, 3, 4, 5},
42 updates: []update{{pos: 2, value: 2}, {pos: 3, value: 3}},
43 queries: []query{{"range", 1, 5}, {"range", 1, 3}, {"range", 3, 5}},
44 expected: []int{20, 11, 15},
45 },
46 {
47 description: "test array with size 5, single index updates and point queries",
48 array: []int{1, 2, 3, 4, 5},
49 updates: []update{{pos: 2, value: 2}, {pos: 3, value: 3}},
50 queries: []query{{"point", 3, 3}, {"point", 1, 1}, {"point", 5, 5}},
51 expected: []int{11, 1, 20},
52 },
53 }
54
55 for _, test := range fenwickTreeTestData {
56 t.Run(test.description, func(t *testing.T) {
57 fenwickTree := fenwicktree.NewFenwickTree(test.array)
58
59 for i := 0; i < len(test.updates); i++ {
60 fenwickTree.Add(test.updates[i].pos, test.updates[i].value)
61 }
62
63 for i := 0; i < len(test.queries); i++ {
64
65 var result int
66
67 if test.queries[i].queryType == "point" {
68 result = fenwickTree.PrefixSum(test.queries[i].firstIndex)
69 } else {
70 result = fenwickTree.RangeSum(test.queries[i].firstIndex, test.queries[i].lastIndex)
71 }
72
73 if result != test.expected[i] {
74 t.Logf("FAIL: %s", test.description)
75 t.Fatalf("Expected result: %d\nFound: %d\n", test.expected[i], result)
76 }

Callers

nothing calls this directly

Calls 4

AddMethod · 0.95
PrefixSumMethod · 0.95
RangeSumMethod · 0.95
NewFenwickTreeFunction · 0.92

Tested by

no test coverage detected