【发布时间】:2017-04-16 20:08:50
【问题描述】:
如果给定一组数值和一个 HashTable 大小,我如何模拟碰撞次数?
【问题讨论】:
-
到目前为止你做了哪些研究?
-
冲突的数量取决于你的哈希算法,所以没有一个万能的答案。
如果给定一组数值和一个 HashTable 大小,我如何模拟碰撞次数?
【问题讨论】:
计算集合中数字值的哈希值并计算重复哈希值的数量。
一个简单的实现可能是:
List<Integer> yourValues = /* Your set of numbers */;
Map<Integer, Set<Integer>> map = new HashMap<>();
// Insert all elements into buckets based on their hash value
yourValues.forEach(value -> {
if (!map.containsKey(value.hashCode()))
map.put(value.hashCode(), new HashSet<>());
map.get(value.hashCode()).add(value);
});
// Sum up the number of values in each bucket, subtract the number of buckets, so only duplicate values are counted
int collisions = map.values().stream().map(Set::size).reduce(0, Integer::sum) - map.size();
System.out.printf("Number of collisions: %d\n", collisions);
【讨论】: