bitmap原理及实现

原理

以二进制位来表示数字
例如:第27位为1,第28位为0。表示在map中27存在28不存在

实现

在这里插入图片描述

代码

<?php
class bitMap
{
    protected $intBitSize = null;
    protected $intBitSizeLog2 = null;
    protected $map = [];

    /**
     * bitMap constructor.
     * @param $maxArg map最大数
     */
    public function __construct($maxArg)
    {
        $this->intBitSize = PHP_INT_SIZE * 8;
        $this->intBitSizeLog2 = log(PHP_INT_SIZE * 8, 2);
        $this->map = array_fill(0, (($maxArg>>$this->intBitSizeLog2) + 1), 0);
    }

    /**
     * 添加, 即设置对应位为1
     * @param $arg
     * @return $this
     */
    public function set($arg)
    {
        if (is_array($arg)) {
            foreach ($arg as $v) {
                list($index, $position) = $this->getLocation($v);
                $this->map[$index] |= 1<<$position;
            }
        } else {
            list($index, $position) = $this->getLocation($arg);
            $this->map[$index] |= 1<<$position;
        }
        return $this;
    }

    /**
     * 判断数字是否存在
     * @param $arg
     * @return bool
     */
    public function get($arg)
    {
        list($index, $position) = $this->getLocation($arg);
        $condition = ($this->map[$index] & 1<<$position) != 0;
        return $condition;
    }

    /**
     * 删除, 即设置对应位为0
     * @param $arg
     * @return $this
     */
    public function del($arg)
    {
        if (is_array($arg)) {
            foreach ($arg as $v) {
                list($index, $position) = $this->getLocation($v);
                $this->map[$index] &= ~(1<<$position);
            }
        } else {
            list($index, $position) = $this->getLocation($arg);
            $this->map[$index] &= ~(1<<$position);
        }
        return $this;
    }

    /**
     * 获取数字对应的位置下标
     * @param $arg
     * @return array
     */
    protected function getLocation($arg)
    {
        return [
            $arg>>$this->intBitSizeLog2,
            $arg%$this->intBitSize
        ];
    }
}

测试

<?php
$map = new bitMap(9999);

for ($i=1; $i<10000; $i++) {
    $map->set($i);
}
$map->del(123);
$map->del(9998);

var_dump(
    [
        1 => $map->get(1),
        99 => $map->get(99),
        123 => $map->get(123),
        9998 => $map->get(9998),
        9999 => $map->get(9999)
    ]
);
//array(5) {
//    [1]=> bool(true)
//  [99]=> bool(true)
//  [123]=> bool(false)
//  [9998]=> bool(false)
//  [9999]=> bool(true)
//}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值