Search code examples
rubybitnarray

What is the fastest way of summing set bits in Ruby's NArray?


I used NArray to implement a bit array, but I am not quite satisfied with the speed of the bits_on method. Currently I have:

# Method that returns the number of bits set "on" in a bit array.
def bits_on
  bits_on = 0

  self.byte_array.each do |byte|
    bits_on += @count_array[byte]
  end

  bits_on
end

byte_array is an NArray.byte() type, and @count_array is build like this:

# Method that returns an array where the element index value is
# the number of bits set for that index value.
def init_count_array
  count_array = []

  (0 ... (2 ** BitsInChar)).each do |i|
    count_array << bits_in_char(i)
  end

  count_array
end

Ideas?

Cheers,

Martin


Solution

  • I am not sure I understand the background correctly, a possible solution is:

    def bits_on
      NArray.to_na(@count_array)[self.byte_array].sum
    end
    

    Sorry, the above is wrong, the next will work:

    def bits_on
      index = NArray.int(*self.byte_array.shape)
      index[] = self.byte_array
      NArray.to_na(@count_array)[index].sum
    end