File tree Expand file tree Collapse file tree 1 file changed +8
-7
lines changed Expand file tree Collapse file tree 1 file changed +8
-7
lines changed Original file line number Diff line number Diff line change 1
1
class BitArray
2
2
attr_reader :size
3
+ attr_reader :field
3
4
include Enumerable
4
-
5
+
5
6
ELEMENT_WIDTH = 32
6
-
7
+
7
8
def initialize ( size )
8
9
@size = size
9
10
@field = Array . new ( ( ( size - 1 ) / ELEMENT_WIDTH ) + 1 , 0 )
10
11
end
11
-
12
+
12
13
# Set a bit (1/0)
13
14
def []=( position , value )
14
15
if value == 1
@@ -17,22 +18,22 @@ def []=(position, value)
17
18
@field [ position / ELEMENT_WIDTH ] ^= 1 << ( position % ELEMENT_WIDTH )
18
19
end
19
20
end
20
-
21
+
21
22
# Read a bit (1/0)
22
23
def []( position )
23
24
@field [ position / ELEMENT_WIDTH ] & 1 << ( position % ELEMENT_WIDTH ) > 0 ? 1 : 0
24
25
end
25
-
26
+
26
27
# Iterate over each bit
27
28
def each ( &block )
28
29
@size . times { |position | yield self [ position ] }
29
30
end
30
-
31
+
31
32
# Returns the field as a string like "0101010100111100," etc.
32
33
def to_s
33
34
inject ( "" ) { |a , b | a + b . to_s }
34
35
end
35
-
36
+
36
37
# Returns the total number of bits that are set
37
38
# (The technique used here is about 6 times faster than using each or inject direct on the bitfield)
38
39
def total_set
You can’t perform that action at this time.
0 commit comments