|
| 1 | +package com.thealgorithms.datastructures.crdt; |
| 2 | + |
| 3 | +import java.util.HashMap; |
| 4 | +import java.util.Map; |
| 5 | + |
| 6 | +/** |
| 7 | + * G-Counter (Grow-only Counter) is a state-based CRDT (Conflict-free Replicated Data Type) |
| 8 | + * designed for tracking counts in a distributed and concurrent environment. |
| 9 | + * Each process maintains its own counter, allowing only increments. The total count |
| 10 | + * is obtained by summing individual process counts. |
| 11 | + * This implementation supports incrementing, querying the total count, |
| 12 | + * comparing with other G-Counters, and merging with another G-Counter |
| 13 | + * to compute the element-wise maximum. |
| 14 | + * (https://en.wikipedia.org/wiki/Conflict-free_replicated_data_type) |
| 15 | + * |
| 16 | + * @author itakurah (https://github.com/itakurah) |
| 17 | + */ |
| 18 | + |
| 19 | +class GCounter { |
| 20 | + private final Map<Integer, Integer> P; |
| 21 | + private final int myId; |
| 22 | + private final int n; |
| 23 | + |
| 24 | + /** |
| 25 | + * Constructs a G-Counter for a cluster of n nodes. |
| 26 | + * |
| 27 | + * @param n The number of nodes in the cluster. |
| 28 | + */ |
| 29 | + public GCounter(int myId, int n) { |
| 30 | + this.myId = myId; |
| 31 | + this.n = n; |
| 32 | + this.P = new HashMap<>(); |
| 33 | + |
| 34 | + for (int i = 0; i < n; i++) { |
| 35 | + P.put(i, 0); |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + /** |
| 40 | + * Increments the counter for the current node. |
| 41 | + */ |
| 42 | + public void increment() { |
| 43 | + P.put(myId, P.get(myId) + 1); |
| 44 | + } |
| 45 | + |
| 46 | + /** |
| 47 | + * Gets the total value of the counter by summing up values from all nodes. |
| 48 | + * |
| 49 | + * @return The total value of the counter. |
| 50 | + */ |
| 51 | + public int value() { |
| 52 | + int sum = 0; |
| 53 | + for (int v : P.values()) { |
| 54 | + sum += v; |
| 55 | + } |
| 56 | + return sum; |
| 57 | + } |
| 58 | + |
| 59 | + /** |
| 60 | + * Compares the state of this G-Counter with another G-Counter. |
| 61 | + * |
| 62 | + * @param other The other G-Counter to compare with. |
| 63 | + * @return True if the state of this G-Counter is less than or equal to the state of the other G-Counter. |
| 64 | + */ |
| 65 | + public boolean compare(GCounter other) { |
| 66 | + for (int i = 0; i < n; i++) { |
| 67 | + if (this.P.get(i) > other.P.get(i)) { |
| 68 | + return false; |
| 69 | + } |
| 70 | + } |
| 71 | + return true; |
| 72 | + } |
| 73 | + |
| 74 | + /** |
| 75 | + * Merges the state of this G-Counter with another G-Counter. |
| 76 | + * |
| 77 | + * @param other The other G-Counter to merge with. |
| 78 | + */ |
| 79 | + public void merge(GCounter other) { |
| 80 | + for (int i = 0; i < n; i++) { |
| 81 | + this.P.put(i, Math.max(this.P.get(i), other.P.get(i))); |
| 82 | + } |
| 83 | + } |
| 84 | +} |
0 commit comments