1. 程式人生 > 實用技巧 >PHP演算法實現bitmap

PHP演算法實現bitmap

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的長度