我使用NArray实现了一个位数组,但我对bits_on方法的速度不太满意。目前我有:
# 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
是NArray.byte()类型,@count_array
是这样构建的:
# 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
想法?
干杯,
马丁
答案 0 :(得分:1)
我不确定我是否正确理解背景,可能的解决方案是:
def bits_on
NArray.to_na(@count_array)[self.byte_array].sum
end
抱歉,以上是错误的,接下来会有效:
def bits_on
index = NArray.int(*self.byte_array.shape)
index[] = self.byte_array
NArray.to_na(@count_array)[index].sum
end