File: tree_test.go

package info (click to toggle)
golang-github-bboreham-go-loser 0.0~git20230920.fcc2c21-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 92 kB
  • sloc: makefile: 2
file content (111 lines) | stat: -rw-r--r-- 2,185 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package loser_test

import (
	"math"
	"testing"

	"github.com/bboreham/go-loser"
)

type List struct {
	list []uint64
	cur  uint64
}

func NewList(list ...uint64) *List {
	return &List{list: list}
}

func (it *List) At() uint64 {
	return it.cur
}

func (it *List) Next() bool {
	if len(it.list) > 0 {
		it.cur = it.list[0]
		it.list = it.list[1:]
		return true
	}
	it.cur = 0
	return false
}

func (it *List) Seek(val uint64) bool {
	for it.cur < val && len(it.list) > 0 {
		it.cur = it.list[0]
		it.list = it.list[1:]
	}
	return len(it.list) > 0
}

func checkIterablesEqual[E loser.Value, S1 loser.Sequence[E], S2 loser.Sequence[E]](t *testing.T, a S1, b S2, less func(E, E) bool) {
	t.Helper()
	count := 0
	for a.Next() {
		count++
		if !b.Next() {
			t.Fatalf("b ended before a after %d elements", count)
		}
		if less(a.At(), b.At()) || less(b.At(), a.At()) {
			t.Fatalf("position %d: %v != %v", count, a.At(), b.At())
		}
	}
	if b.Next() {
		t.Fatalf("a ended before b after %d elements", count)
	}
}

func TestMerge(t *testing.T) {
	tests := []struct {
		name string
		args []*List
		want *List
	}{
		{
			name: "empty input",
			want: NewList(),
		},
		{
			name: "one list",
			args: []*List{NewList(1, 2, 3, 4)},
			want: NewList(1, 2, 3, 4),
		},
		{
			name: "two lists",
			args: []*List{NewList(3, 4, 5), NewList(1, 2)},
			want: NewList(1, 2, 3, 4, 5),
		},
		{
			name: "two lists, first empty",
			args: []*List{NewList(), NewList(1, 2)},
			want: NewList(1, 2),
		},
		{
			name: "two lists, second empty",
			args: []*List{NewList(1, 2), NewList()},
			want: NewList(1, 2),
		},
		{
			name: "two lists b",
			args: []*List{NewList(1, 2), NewList(3, 4, 5)},
			want: NewList(1, 2, 3, 4, 5),
		},
		{
			name: "two lists c",
			args: []*List{NewList(1, 3), NewList(2, 4, 5)},
			want: NewList(1, 2, 3, 4, 5),
		},
		{
			name: "three lists",
			args: []*List{NewList(1, 3), NewList(2, 4), NewList(5)},
			want: NewList(1, 2, 3, 4, 5),
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			less := func(a, b uint64) bool { return a < b }
			lt := loser.New[uint64](tt.args, math.MaxUint64)
			checkIterablesEqual(t, tt.want, lt, less)
		})
	}
}