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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
use super::Weight;
use std::{collections::HashMap, hash::Hash};
#[derive(Copy, Clone, Debug)]
struct SmoothWeightItem<T> {
item: T,
weight: isize,
current_weight: isize,
effective_weight: isize,
}
#[derive(Default)]
pub struct SmoothWeight<T> {
items: Vec<SmoothWeightItem<T>>,
n: isize,
}
impl<T: Copy + PartialEq + Eq + Hash> SmoothWeight<T> {
pub fn new() -> Self {
SmoothWeight {
items: Vec::new(),
n: 0,
}
}
fn next_smooth_weighted(&mut self) -> Option<SmoothWeightItem<T>> {
let mut total = 0;
let mut best = self.items[0];
let mut best_index = 0;
let mut found = false;
let items_len = self.items.len();
for i in 0..items_len {
self.items[i].current_weight += self.items[i].effective_weight;
total += self.items[i].effective_weight;
if self.items[i].effective_weight < self.items[i].weight {
self.items[i].effective_weight += 1;
}
if !found || self.items[i].current_weight > best.current_weight {
best = self.items[i];
found = true;
best_index = i;
}
}
if !found {
return None;
}
self.items[best_index].current_weight -= total;
Some(best)
}
}
impl<T: Copy + PartialEq + Eq + Hash> Weight for SmoothWeight<T> {
type Item = T;
fn next(&mut self) -> Option<T> {
if self.n == 0 {
return None;
}
if self.n == 1 {
return Some(self.items[0].item);
}
let rt = self.next_smooth_weighted()?;
Some(rt.item)
}
fn add(&mut self, item: T, weight: isize) {
let weight_item = SmoothWeightItem {
item,
weight,
current_weight: 0,
effective_weight: weight,
};
self.items.push(weight_item);
self.n += 1;
}
fn all(&self) -> HashMap<T, isize> {
let mut rt: HashMap<T, isize> = HashMap::new();
for w in &self.items {
rt.insert(w.item, w.weight);
}
rt
}
fn remove_all(&mut self) {
self.items.clear();
self.n = 0;
}
fn reset(&mut self) {
for w in &mut self.items {
w.current_weight = 0;
w.effective_weight = w.weight;
}
}
}
#[cfg(test)]
mod tests {
use crate::{SmoothWeight, Weight};
use std::collections::HashMap;
#[test]
fn test_smooth_weight() {
let mut sw: SmoothWeight<&str> = SmoothWeight::new();
sw.add("server1", 5);
sw.add("server2", 2);
sw.add("server3", 3);
let mut results: HashMap<&str, usize> = HashMap::new();
for _ in 0..100 {
let s = sw.next().unwrap();
*results.entry(s).or_insert(0) += 1;
}
assert_eq!(results["server1"], 50);
assert_eq!(results["server2"], 20);
assert_eq!(results["server3"], 30);
}
}