【发布时间】:2011-03-02 05:28:52
【问题描述】:
我正在 c 中为家庭作业制作一个哈希集 ADT。我终其一生都无法弄清楚为什么我的逻辑不适用于计算哈希集中集群的函数。
void printClusterStats (hashset_ref hashset) {
int **clusters = (int**)calloc (hashset->length, sizeof(int));
assert (clusters);
int ct = 0;
// i traverses hashset->array
// ct adds up words in each cluster
// this loop screws up vvv
for ( int i = 0; i < hashset->length; ++i) {
if (hashset->array[i] == NULL) {
clusters[ct] += 1;
ct = 0;
}else {
ct += 1;
}
}
clusters[ct] +=1; //catch an ending cluster
printf("%10d words in the hash set\n", hashset->load);
printf("%10d length of the hash array\n", hashset->length);
for ( int i = 0; i < hashset->length; i++){
if (clusters[i] == 0) continue;
else{
printf("%10d clusters of size %3d\n", clusters[i], i);
}
}
free(clusters);
}
这个函数的输出如下:
26 words in the hash set
63 length of the hash array
96 clusters of size 0
32 clusters of size 1
16 clusters of size 2
4 clusters of size 4
4 clusters of size 6
305 clusters of size 33
-703256008 clusters of size 34
-703256008 clusters of size 35
对于我的输入哈希集,63 长的数组中有 26 个单词。然而,计数以某种方式搞砸了。
编辑:我手动计算了集群,发现每个计数都是应有的 4 倍。这是什么意思?
【问题讨论】:
标签: c arrays pointers data-structures hashset