-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsubset_test.go
108 lines (94 loc) · 2.18 KB
/
subset_test.go
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
package main
import (
"fmt"
"slices"
"sort"
"testing"
)
var Subset bool
type subsetBench func(first []int, second []int) bool
func BenchmarkSubset(b *testing.B) {
for _, sizeFirst := range sizes {
for _, sizeSecond := range sizes {
if sizeFirst > sizeSecond {
continue
}
b.Run(
fmt.Sprintf("slice(%d)(%d)", sizeFirst, sizeSecond),
benchmarkSubset(sizeFirst, sizeSecond, subsetSlice),
)
b.Run(
fmt.Sprintf("slice_sort_binsearch(%d)(%d)", sizeFirst, sizeSecond),
benchmarkSubset(sizeFirst, sizeSecond, subsetSortBinSearch),
)
b.Run(
fmt.Sprintf("map(%d)(%d)", sizeFirst, sizeSecond),
benchmarkSubset(sizeFirst, sizeSecond, subsetMap),
)
}
}
}
func benchmarkSubset(sizeFirst, sizeSecond int, runF subsetBench) func(*testing.B) {
// Slice A is smaller copy of Slice B, this is to force worst case for
// for loop approach, so that it iterates all the values.
second := testingSlice(sizeSecond)
first := second[:sizeFirst]
return func(b *testing.B) {
var f bool
for n := 0; n < b.N; n++ {
f = runF(first, second)
}
Subset = f
}
}
func subsetSlice(first, second []int) bool {
if len(first) > len(second) {
return false
}
for _, firstValue := range first {
var found bool
for _, secondValue := range second {
if firstValue == secondValue {
found = true
break
}
}
if !found {
return false
}
}
return true
}
func subsetSortBinSearch(first, second []int) bool {
if len(first) > len(second) {
return false
}
// Need to copy because sort modifies the slice.
// This adds time to the execution, but it is ok because
// the other implementations don't have to do this.
var secondCopy = make([]int, len(second))
copy(secondCopy, second)
sort.Ints(secondCopy)
for _, firstValue := range first {
_, found := slices.BinarySearch(secondCopy, firstValue)
if !found {
return false
}
}
return true
}
func subsetMap(first, second []int) bool {
if len(first) > len(second) {
return false
}
set := make(map[int]struct{}, len(second))
for _, value := range second {
set[value] = struct{}{}
}
for _, value := range first {
if _, found := set[value]; !found {
return false
}
}
return true
}