【问题标题】:How do I count the number of collisions in a HashTable from a set of values? [closed]如何从一组值中计算 HashTable 中的冲突次数? [关闭]
【发布时间】:2017-04-16 20:08:50
【问题描述】:

如果给定一组数值和一个 HashTable 大小,我如何模拟碰撞次数?

【问题讨论】:

  • 到目前为止你做了哪些研究?
  • 冲突的数量取决于你的哈希算法,所以没有一个万能的答案。

标签: java hashtable


【解决方案1】:

计算集合中数字值的哈希值并计算重复哈希值的数量。

一个简单的实现可能是:

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);

【讨论】:

  • 谢谢你。但是,我对 yourObjects 是什么数据类型有点困惑。你能澄清一下吗?
  • 它是整数值的集合。可能是 List 或 Set。我改变了答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-03
  • 2019-01-27
  • 1970-01-01
  • 1970-01-01
  • 2013-02-04
相关资源
最近更新 更多