Skip to content

Instantly share code, notes, and snippets.

@shosanna
Created March 18, 2014 12:06
Show Gist options
  • Save shosanna/9618794 to your computer and use it in GitHub Desktop.
Save shosanna/9618794 to your computer and use it in GitHub Desktop.
class BooleanArray
attr_reader :length
attr_reader :used_length
def initialize(length)
@length = length
@used_length = 0
@inner = Array.new((length - 1) / 8 + 1, 0)
end
private
def get_byte_bit(index)
return [index / 8, index % 8]
end
public
# get(i)
def [](index)
raise IndexOutOfBoundsException.new(index, @length) if (index < 0 || index >= @used_length)
byte, bit = get_byte_bit(index)
return ((@inner[byte]) & (1 << bit)) != 0
end
# set(i, value)
# always returns value
def []=(index, value)
raise IndexOutOfBoundsException.new(index, @length) if (index < 0 || index >= @length)
raise BooleanExpectedException.new(value) unless value.instance_of?(TrueClass) || value.instance_of?(FalseClass)
byte, bit = get_byte_bit(index)
if value
@inner[byte] |= 1 << bit
else
@inner[byte] &= 255 - (1 << bit)
end
@used_length = index + 1 if index >= @used_length
return value
end
# find(value)
# returns nil when value is not found
def find(value)
# TODO
raise BooleanExpectedException.new(value) unless value.instance_of?(TrueClass) || value.instance_of?(FalseClass)
@used_length.times do |i|
if value
return ((@inner[] & (1 << i) != 0)
else
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment