GCounter
这段代码实现了一个GCounter,是一个分布式计数器,支持增加计数和合并计数器。GCounter是一种弱一致性的数据结构,可以用于分布式系统中的计数场景。
其中,zero()函数返回一个空的计数器,value(c)函数返回计数器c的总和,inc(c, key)函数将计数器c中key的计数加1,merge(a, b)函数将计数器a和b合并,返回一个新的计数器,新计数器中每个key的值为a和b中对应key的值的最大值。
import java.util.HashMap;
import java.util.Map;
public class GCounter {
private Map<String, Integer> counter;
public GCounter() {
counter = new HashMap<>();
}
public int value() {
int sum = 0;
for (int count : counter.values()) {
sum += count;
}
return sum;
}
public void inc(String key) {
counter.put(key, counter.getOrDefault(key, 0) + 1);
}
public void merge(GCounter other) {
for (Map.Entry<String, Integer> entry : other.counter.entrySet()) {
String key = entry.getKey();
int value = entry.getValue();
counter.put(key, Math.max(counter.getOrDefault(key, 0), value));
}
}
}
GCounter = dict
def zero():
return GCounter()
def value(c: GCounter):
return sum(c.values())
def inc(c: GCounter, key):
c[key] = c.get(key, 0) + 1
return c
def merge(a: GCounter, b:GCounter):
return { key: max(a.get(key, 0), b.get(key, 0)) for key in set(a.keys()) | set(b.keys()) }
标签:return,GCounter,counter,value,CRDT,计数器,key,工具
From: https://www.cnblogs.com/sleepday/p/17259000.html