public class Solution {
// Number of range
private int n;
// Number of machines
private int k;
private Set<Integer> ids;
private Map<Integer, List<Integer>> machines;
// @param n a positive integer
// @param k a positive integer
// @return a Solution object
public static Solution create(int n, int k) {
// Write your code here
Solution solution = new Solution();
solution.n = n;
solution.k = k;
solution.ids = new HashSet<>();
solution.machines = new HashMap<>();
return solution;
}
// @param machine_id an integer
// @return a list of shard ids
public List<Integer> addMachine(int machine_id) {
Random rand = new Random();
List<Integer> virtualNodes = new ArrayList<>();
for (int i = 0; i < k; i++) {
int index = rand.nextInt(n);
while (ids.contains(index)) {
index = rand.nextInt(n);
}
ids.add(index);
virtualNodes.add(index);
}
Collections.sort(virtualNodes);
machines.put(machine_id, virtualNodes);
return virtualNodes;
}
// @param hashcode an integer
// @return a machine id
public int getMachineIdByHashCode(int hashcode) {
int distance = Integer.MAX_VALUE;
int diff = 0;
int machineId = 0;
for (Map.Entry<Integer, List<Integer>> entry : machines.entrySet()) {
int key = entry.getKey();
List<Integer> virtualNodes = entry.getValue();
for (int node : virtualNodes) {
diff = node - hashcode;
if (diff < 0) {
diff += n;
}
if (diff < distance) {
distance = diff;
machineId = key;
}
}
}
return machineId;
}
}