# Arrays Introduction
strings = ["a", "b", "c", "d"]
# 4x4 = 16 bytes of storage
# push
strings.push("e")
p strings
# pop
strings.pop
strings.pop
p strings
# unshift
strings.unshift("x")
p strings
p "==============Implementation of an Array class=============="
class Arr
attr_accessor :length, :data
def initialize
@length = 0
@data = {}
end
def get(index)
data[index]
end
def push(item)
data[@length] = item
@length += 1
end
def pop
last_item = data[@length - 1]
@data.delete(@length-1)
@length -= 1
last_item
end
def delete(index)
item = @data[index]
shift_items(index)
item
end
def shift_items(index)
for i in index..(@length-1)
@data[i] = @data[i+1]
end
@data.delete(@length-1)
@length -= 1
end
end
arr = Arr.new
p arr.get(0)
arr.push("Hi")
arr.push("you")
arr.push("are")
arr.push("!")
arr.push("!")
p arr.pop
arr.push("nice")
p arr
p arr.delete(3)
p arr
p "==============Reverse a string=============="
str = "I am the king"
def reverse_str(str)
return if str == nil || str.length < 2 || str.class != String
backwards = []
for i in str.length.downto(0)
backwards << str[i]
end
backwards.join("")
end
p str
p reverse_str(str)
p "==============Merge two sorted arrays=============="
arr1 = [1,2,4,6,8]
arr2 = [3,6,12,45,78]
def merge_sorted_arrays(arr1, arr2)
arr1_item = arr1[0]
arr2_item = arr2[0]
i = 0
j = 0
merged_array = []
while (arr1_item || arr2_item)
if arr2_item.nil? || (arr1_item && arr1_item < arr2_item)
merged_array.push(arr1_item)
i += 1
arr1_item = arr1[i]
else
merged_array.push(arr2_item)
j += 1
arr2_item = arr2[j]
end
end
merged_array
end
p merge_sorted_arrays(arr1, arr2)
To embed this project on your website, copy the following code and paste it into your website's HTML: