-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathp01_int_set.rb
115 lines (88 loc) · 1.62 KB
/
p01_int_set.rb
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
class MaxIntSet
def initialize(max)
@store = Array.new(max, false)
end
def insert(num)
validate!(num)
if @store[num - 1] == false
@store[num - 1] = true
end
end
def remove(num)
validate!(num)
if @store[num -1] == true
@store[num -1] = false
end
end
def include?(num)
validate!(num)
@store[num -1]
end
private
def is_valid?(num)
return true if num.between?(0, @store.count - 1)
false
end
def validate!(num)
raise "Out of bounds" unless is_valid?(num)
end
end
class IntSet
def initialize(num_buckets = 20)
@store = Array.new(num_buckets) { Array.new }
end
def insert(num)
self[num] << num
end
def remove(num)
# raise 'Not included' unless @store.include?(num)
self[num].pop
end
def include?(num)
self[num] == [num]
end
private
def [](num)
# self[num]
@store[num % num_buckets]
end
def num_buckets
@store.length
end
end
class ResizingIntSet
attr_reader :count
def initialize(num_buckets = 20)
@store = Array.new(num_buckets) { Array.new }
@count = 0
end
def insert(num)
self[num] << num
@count += 1
if @count > num_buckets
resize!
end
end
def remove(num)
self[num].pop
@count -= 1
end
def include?(num)
self[num].include?(num)
end
private
def [](num)
@store[num % num_buckets]
end
def num_buckets
@store.length
end
def resize!
placeholder_arr = @store.flatten
@store += Array.new(num_buckets) { Array.new }
placeholder_arr.each do |el|
insert(el)
@count -= 1
end
end
end