c - 关于哈希函数

标签 c algorithm hash

让我们考虑一个二维数组,声明如下:

#include <stdbool.h>

bool array[N1][N2];

我必须知道这个数组的每一行是否恰好有一个true相同位置的值。

例如以下内容就可以:

{ 
  { 1, 0, 1, 0 },
  { 1, 0, 0, 1 },
  { 0, 0, 1, 1 }
}

然而这是不正确的:

{ 
  { 1, 0, 1, 0 },
  { 1, 0, 1, 0 },
  { 0, 0, 1, 1 }
}

我已经尝试过这个:

static uintmax_t hash(const bool *t, size_t n) 
{
    uintmax_t retv = 0U;
    for (size_t i = 0; i < n; ++i)
        if (t[i] == true)
            retv |= 1 << i;
    return retv;
}

static int is_valid(bool n) 
{ 
    return n != 0 && (n & (n - 1)) == 0;
}

bool check(bool t[N1][N2])
{
    uintmax_t thash[N1];

    for (size_t i = 0; i < N1; ++i)
        thash[i] = hash(t[i], N2);

    for (size_t i = 0; i < N1; ++i)
        for (size_t j = 0; j < N1; ++j)
            if (i != j && !is_valid(thash[i] & thash[j]))
                return 0;

    return 1;
}

但它仅适用于 N1 <= sizeof(uintmax_t) * CHAR_BIT 。你知道解决这个问题的最佳方法吗?

最佳答案

为什么不创建另一个大小为 N2(列数)的数组,将其设置为全部 true,然后将其设置为每行中的每一列。最后,检查您的新数组是否恰好有一个设置位。

bool array[N1][N2];  // this is initialized somehow
bool result[N2];
int i, j;

// initialize result array
for (j = 0; j < N2; ++j)
{
    result[j] = 1;
}

// Now go through the array, computing the result
for (i = 0; i < N1; ++i)
{
    for (j = 0; j < N2; ++j)
    {
        result[j] &= array[i][j];
    }
}

// At this point, you can check the result array.
// If your array is valid, then result should have only one '1' in it.

关于c - 关于哈希函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13183384/

相关文章:

mysql - MySQL 中的哈希索引算法

c++ - 以字符串 vector 为值的 hashMap

c - 如何将数组传递给函数?指针?

c - Getopt - 需要输入

c - C编程中的修改链表

algorithm - 找到所有最小生成树

perl - 序列化 Perl 包变量并从 CGI 脚本每 24 小时更新一次

c - KAA 无法创建 kaa_configuration_manager_set_root_receiver

java - 在Java中的未排序整数数组中查找恰好出现一次的整数

javascript - 在 javascript 对象数组中找到缺失的元素?