-
Notifications
You must be signed in to change notification settings - Fork 0
/
custom_set.rb
58 lines (44 loc) · 886 Bytes
/
custom_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
require_relative "fixed_size_array"
class CustomSet
def initialize
@size = 0
@elements = FixedSizeArray.new(size)
end
def is_empty?
size == 0
end
def add element
return if contains(element)
add_memory
@elements[size] = element
@size += 1
@empty = false
end
def size
@size
end
def contains element
index_of(element) >= 0
end
def remove element
index = index_of(element)
return unless index >= 0
@elements[index] = @elements[size-1]
@elements[size-1] = nil
@size -= 1
end
private
def add_memory mem_size= 1
new_elements= FixedSizeArray.new(size + mem_size)
for i in (0..size-1)
new_elements[i] = @elements[i]
end
@elements = new_elements
end
def index_of element
for i in (0..size-1)
return i if @elements[i] == element
end
return -1
end
end