]> git.donarmstrong.com Git - biopieces.git/blobdiff - code_ruby/lib/maasha/bitarray.rb
added more methods to bitarray.rb
[biopieces.git] / code_ruby / lib / maasha / bitarray.rb
index e65ab3ca4429f9be7da258c6bb8a2f1f8b0dc673..1b2bc9ea212268c5650f44c63c58f2a6d6ceaf99 100644 (file)
@@ -155,6 +155,63 @@ class BitArray
 
   alias :to_string :to_s
 
+  # Method to set the bits to "on" in an interval in a bit array.
+  # Returns the number of bits set.
+  def interval_set(start, stop)
+    raise BitArrayError, "interval start < 0 (#{start} < 0)"                      if start < 0
+    raise BitArrayError, "interval stop > bit array size (#{stop} > #{self.size})" if stop  > self.size
+    raise BitArrayError, "interval stop < interval start (#{stop} < #{start})"    if stop  < start
+
+    (start ... stop).each do |pos|
+      self.bit_set(pos)
+    end
+
+    stop - start
+  end
+
+  # Method to set the bits to "off" in an interval in a bit array.
+  # Returns the number of bits unset.
+  def interval_unset(start, stop)
+    raise BitArrayError, "interval start < 0 (#{start} < 0)"                      if start < 0
+    raise BitArrayError, "interval stop > bit array size (#{stop} > #{self.size})" if stop  > self.size
+    raise BitArrayError, "interval stop < interval start (#{stop} < #{start})"    if stop  < start
+
+    (start ... stop).each do |pos|
+      self.bit_unset(pos)
+    end
+
+    stop - start
+  end
+
+  # Method to locate intervals of bits set to "on" in a bit array.
+  #   BitArray.each_interval -> Array
+  #   BitArray.each_interval { |start, stop| } -> Fixnum
+  def each_interval
+    intervals = []
+    start     = 0
+    stop      = 0
+
+    while start < self.size
+      if self.bit_set?(start)
+        stop = start
+
+        while stop < self.size and self.bit_set?(stop)
+          stop += 1
+        end
+
+        if block_given?
+          yield start, stop
+        else
+          intervals << [start, stop]
+        end
+      end
+
+      stop > start ? start = stop : start += 1
+    end
+
+    return intervals unless block_given?
+  end
+
   private
 
   # Method to initialize the byte array (string) that constitutes the bit array.