-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathbitset.rb
More file actions
62 lines (47 loc) · 1.11 KB
/
bitset.rb
File metadata and controls
62 lines (47 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
require "test/unit"
class Bitset
attr_reader :no
def initialize no
@no = no
end
def toggle nth
@no ^= 1 << nth
end
def turn_on nth
@no |= 1 << nth
end
def turn_off nth
@no &= ~(1 << nth)
end
def union set
Bitset.new(@no | set.no)
end
def to_s
"0b#{@no.to_s(2)}"
end
end
class TestBitSet < Test::Unit::TestCase
def setup
@bs = Bitset.new(16) # 0b10000
end
def test_turn_on
@bs.turn_on(nth=0); assert_equal("0b10001", @bs.to_s)
@bs.turn_on(nth=1); assert_equal("0b10011", @bs.to_s)
end
def test_turn_off
@bs.turn_off(nth=0); assert_equal("0b10000", @bs.to_s)
@bs.turn_on (nth=2); assert_equal("0b10100", @bs.to_s)
@bs.turn_off(nth=2); assert_equal("0b10000", @bs.to_s)
end
def test_toggle
@bs.toggle(nth=0); assert_equal("0b10001", @bs.to_s)
@bs.toggle(nth=0); assert_equal("0b10000", @bs.to_s)
@bs.toggle(nth=1); assert_equal("0b10010", @bs.to_s)
@bs.toggle(nth=1); assert_equal("0b10000", @bs.to_s)
end
def test_union
bs1 = Bitset.new(2)
bs2 = @bs.union(bs1)
assert_equal("0b10010", bs2.to_s)
end
end