From 605026c6c6a8270e6af415be90937d6928e4dd7c Mon Sep 17 00:00:00 2001 From: Ropel Date: Wed, 30 May 2018 18:50:38 +0200 Subject: [PATCH] added nextSetBit --- examples/BitArray.php | 16 +++++++++++- src/BitArray/BitArray.php | 51 ++++++++++++++++++++++++++++++++++++++- 2 files changed, 65 insertions(+), 2 deletions(-) diff --git a/examples/BitArray.php b/examples/BitArray.php index e3b2c51..bec2162 100644 --- a/examples/BitArray.php +++ b/examples/BitArray.php @@ -13,7 +13,9 @@ * This file is part of the php-bitarray package https://github.com/chdemko/php-bitarray */ -require __DIR__ . '/../vendor/autoload.php'; +//require __DIR__ . '/../vendor/autoload.php'; +require __DIR__ . '/../src/BitArray/BitArray.php'; +require __DIR__ . '/../src/BitArray/Iterator.php'; use chdemko\BitArray\BitArray; @@ -43,3 +45,15 @@ // Print [true,true,true,false,true] echo json_encode($bits) . PHP_EOL; + +// Print 14 +$bits = BitArray::fromString('1100000000000010'); +echo $bits->nextSetBit(4) . PHP_EOL; + +// print 3 to 30 +for($i = 2;$i < 30; $i++) +{ + $str = str_pad('10',$i,'0'); + $bits = BitArray::fromString($str . '100'); + echo $str . " -- " . $bits->nextSetBit(2) . PHP_EOL; +} diff --git a/src/BitArray/BitArray.php b/src/BitArray/BitArray.php index 7812d94..9e7206d 100644 --- a/src/BitArray/BitArray.php +++ b/src/BitArray/BitArray.php @@ -208,7 +208,8 @@ public function offsetGet($offset) throw new \OutOfRangeException('Argument offset must be a positive integer lesser than the size'); } } - + + /** * Set the truth value for an index * @@ -801,4 +802,52 @@ public function shift($size = 1, $value = false) return $this; } + + + /** + * Returns the index of the first bit that is set to true that occurs on or after the specified starting index. If no such bit exists then -1 is returned. + * + * @param integer $offset The offset + * + * @return boolean The truth value + * + * @throw \OutOfRangeException Argument index must be an positive integer lesser than the size + * + * @since 1.0.0 + */ + public function nextSetBit($offset) + { + if ($this->offsetExists($offset)) + { + $ret = $offset; + while(( $ret % 8 )!=0) + { + if($this[$ret]) + return $ret; + else + $ret++; + } + if (!$this->offsetExists($ret)) + return -1; + while($this->data[(int) ($ret / 8)]==chr(0)) + { + //echo "$ret - " . $this->data[(int) ($ret / 8)] . " !\n"; + $ret += 8; + if (!$this->offsetExists($ret)) + return -2; + } + while($ret < $this->size) + { + if($this[$ret]) + return $ret; + else + $ret++; + } + return -3; + } + else + { + throw new \OutOfRangeException('Argument offset must be a positive integer lesser than the size'); + } + } }