首页 > 编程语言 > 详细

PHP算法实现bitmap

时间:2020-12-08 18:24:42      阅读:35      评论:0      收藏:0      [点我收藏+]

2020年12月8日17:46:01

项目地址:https://gitee.com/zxadmin/phpCommonAlgorithms

<?php

namespace ZX\Algorithm;

/*
 * bitmap算法
 */

final class BitMap {

    //int 位数
    private static $phpIntSize = PHP_INT_SIZE;
    //int最大值  Usually int(2147483647) in 32 bit systems and int(9223372036854775807) in 64 bit systems. Available since PHP 5.0.5
    private static $phpIntMax = PHP_INT_MAX;
    //最大位数64位 1 << 6 32位 1 << 5
    private static $max = (1 << 6 ) - 1;
    //储存数据的变量
    private static $data = [];

    public static function addValue(int $n) {
        //
        $row = $n >> 6;
        //余数
        $index = $n % self::$max;
        //或运算保证占位不被覆盖
        self::$data[$row] |= 1 << $index;
    }

    // 判断所在的bit为是否为1
    public static function exits(int $n) {
        $row = $n >> 6;
        $index = $n % self::$max;

        $result = self::$data[$row] & (1 << $index);
//        p($result);
        return $result != 0;
    }

    public static function getData() {
        return self::$data;
    }

}

原理比较简单,吧数组元素降低维度到二进制数位上,利用商做key,余数作为位数,通过位运算来做数据统计

测试

<?php

include_once ./../src/Algorithm/BitMap.php;
include_once ./../src/Algorithm/BitOperation.php;

include_once ./Function.php;

use ZX\Algorithm\BitMap;

$arr = [0, 1, 3, 16, 42, 69, 18, 11, 99, 32421, 32423, 32525, 9999999999];

foreach ($arr as $v) {
    BitMap::addValue($v);
}

$tt = BitMap::getData();


$rr = BitMap::exits(9999999998);

if ($rr) {
    p(ok);
} else {
    p(no);
}

几个小技巧总结:

任何判断二进制那个位置是1

N:待判断的二进制数
B:待判断的位(右往左)
$n = 11;
p(base_convert($n, 10, 2));
$b = 2;
$rr = $n >> ($b - 1) & 1;
p($rr);
结果:((N>>(B-1))&1

 

注意:$max = (1 << 6 ) - 1; 和 $max = 1 << 6  - 1;

不是一个意思

 

9223372036854775807是64位最大的证书是63的长度

 

PHP算法实现bitmap

原文:https://www.cnblogs.com/zx-admin/p/14104323.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!