Skip to content

Instantly share code, notes, and snippets.

@maxd
Created November 4, 2013 15:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maxd/7303981 to your computer and use it in GitHub Desktop.
Save maxd/7303981 to your computer and use it in GitHub Desktop.
BitArray on Ruby (prototype)
require 'benchmark'
class BitArray
def initialize(capacity = 32 * 1024)
@array = Array.new(capacity, 0)
end
def set(i)
quotient, modulus = i.divmod(32)
@array[quotient] |= 1 << modulus
end
def count
result = 0
for i in @array
c = ((i & 0xfff) * 0x1001001001001 & 0x84210842108421) % 0x1f
c += (((i & 0xfff000) >> 12) * 0x1001001001001 & 0x84210842108421) % 0x1f
c += ((i >> 24) * 0x1001001001001 & 0x84210842108421) % 0x1f
result += c
end
result
end
def substract(bitarray)
result = BitArray.new
i = 0
array_size = @array.size
while i < array_size
result[i] = @array[i] & ~bitarray[i]
i += 1
end
result
end
def intersection(bitarray)
result = BitArray.new
i = 0
array_size = @array.size
while i < array_size
result[i] = @array[i] & bitarray[i]
i += 1
end
result
end
protected
def [](i)
@array[i]
end
def []=(i, v)
@array[i] = v
end
end
bitarray = BitArray.new
puts Benchmark.measure {
1_000_000.times do |i|
bitarray.set(i)
end
}
puts Benchmark.measure {
bitarray.count
}
puts Benchmark.measure {
bitarray.intersection(BitArray.new)
}
puts Benchmark.measure {
bitarray.substract(BitArray.new)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment