/
diversity_rule.go
83 lines (68 loc) · 1.94 KB
/
diversity_rule.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
package sort
import (
"strings"
"github.com/alibaba/pairec/module"
"github.com/alibaba/pairec/recconf"
)
type DiversityMatchFunc func(item *module.Item) bool
type DiversityRule struct {
DiversityRuleConfig recconf.DiversityRuleConfig
DimensionItemMap map[module.ItemId]string
}
func NewDiversityRule(config recconf.DiversityRuleConfig) *DiversityRule {
rule := DiversityRule{
DiversityRuleConfig: config,
DimensionItemMap: make(map[module.ItemId]string),
}
return &rule
}
func (r *DiversityRule) GetDimensionValue(item *module.Item) string {
if value, ok := r.DimensionItemMap[item.Id]; ok {
return value
}
var dimensionValues []string
for _, dimension := range r.DiversityRuleConfig.Dimensions {
value := item.StringProperty(dimension)
dimensionValues = append(dimensionValues, value)
}
r.DimensionItemMap[item.Id] = strings.Join(dimensionValues, "_")
return r.DimensionItemMap[item.Id]
}
func (r *DiversityRule) Match(item *module.Item, itemList []*module.Item) bool {
size := len(itemList)
itemDimensionValue := r.GetDimensionValue(item)
if r.DiversityRuleConfig.IntervalSize > 0 && size >= r.DiversityRuleConfig.IntervalSize {
end := size
begin := size - r.DiversityRuleConfig.IntervalSize
sameValue := 1
for i := end - 1; i >= begin; i-- {
if itemDimensionValue == r.GetDimensionValue(itemList[i]) {
sameValue++
} else {
break
}
}
if sameValue > r.DiversityRuleConfig.IntervalSize {
return false
}
}
if r.DiversityRuleConfig.WindowSize > 0 &&
r.DiversityRuleConfig.FrequencySize > 0 &&
r.DiversityRuleConfig.WindowSize > r.DiversityRuleConfig.FrequencySize {
end := size
begin := size - r.DiversityRuleConfig.WindowSize + 1
if begin < 0 {
begin = 0
}
sameValue := 1
for i := begin; i < end; i++ {
if itemDimensionValue == r.GetDimensionValue(itemList[i]) {
sameValue++
}
if sameValue > r.DiversityRuleConfig.FrequencySize {
return false
}
}
}
return true
}