使用布尔代数实现完美哈希(以A股字冠索引为例)

布尔代数是硬件设计的基础,然而在软件算法设计中也有一席之地。比如从字符串到特定数字之映射,一般使用gperf来实现。

本文演示另外一种思路,就是用布尔代数来实现,以达到更高的效率。

A股字冠目前共有12种,分列如下:

000 0b0000,0000,0000

001 0b0000,0000,0001

002 0b0000,0000,0010

003 0b0000,0000,0011

300 0b0011,0000,0000

600 0b0000,0000,0000

601 0b0110,0000,0001

602 0b0110,0000,0010

603 0b0110,0000,0011

605 0b0110,0000,0101

688 0b0110,1000,1000

689 0b0110,1000,1001

我们看到需要低位的四位及高位的0位及2位共6位二进制数来确定一个字冠,如果将沪市低字节加上5,深市高字节的低位移动到低字节的第二位,则可以用四个二进制位唯一标记一个字冠。

000 0000

001 0001

002 0010

003 0011

300 0100

600 0101

601 0110

602 0111

603 1000

605 1010

688 1101

689 1110

将此结果映射到0~15后,得到四个卡诺图,化简后得到四个逻辑函数如下:

f_3=a

f_2=\bar{a}b

f_1=(a+c)(\bar{a}+b)

f_0=(a+d)(\bar{a}+c)

c++测试代码如下:

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

inline int get_hdr_idx_by_bitop(const int code);
inline int get_hdr_idx_by_bool(const int code);

char hdrs[][8] =
  {
    "000",
    "001",
    "002",
    "003",
    "300",
    "600",
    "601",
    "602",
    "603",
    "605",
    "688",
    "689"
  };

int main(void)
{
  for(int ii=0; ii<12; ++ii)
    {
      auto hdrptr = hdrs[ii];
      int securitycode = strtol(hdrptr, nullptr, 16);
      int idx1 = get_hdr_idx_by_bitop(securitycode);
      int idx2 = get_hdr_idx_by_bool(securitycode);
      printf("hdr[%d,%d]=%06x\n", idx1, idx2, securitycode);
    }
  exit(0);
}
int get_hdr_idx_by_bitop(const int code)
{
  int a;

  a = 0xf & code;
  int h0 = (code >> 8) & 1;
  int h2 = (code >> 10) & 1;
  int l2 = (code >> 2) & 1;
  int l3 = (code >> 3) & 1;

  a += (((h0 | h2) << (2-l3)) | (h2 ^ (l2 ^ l3)));
  return a;
}
int get_hdr_idx_by_bool(const int code)
{
  int a, b, c, d, e;

  a = 0xf & code;
  int h0 = (code >> 8) & 1;
  int h2 = (code >> 10) & 1;

  a += ((h0 | h2) << 2) | h2;

  d = a & 1; a >>= 1;

  c = a & 1; a >>= 1;

  b = a & 1; a >>= 1;

  e = ~a;
  return ((a << 3)
          | ((e & b) << 2)
          | (((a | c) & (e | b)) << 1)
          | ((a | d) & (e | c)));
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值