Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions array_problems/arrays.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,27 @@

module ArrayUtil
def self.max(array)
#I found this solution in the Pry Debugger notes. I think it would take some time to execute because I assume it goes through every item in the array, since it's an inject.
array.inject {|y, x| x > y ? x : y }
end

def self.middle_element(array)
#I don't think these would require too much time because the if/else is based on the array length, which is pre-defined in the array.
if array.length == 0
nil
elsif array.length % 2 == 0
mid = array.length/2
(array[mid] + array[mid - 1])/2.to_f
else
mid = array.length/2
array[mid]
end
end

def self.sum_arrays(array1, array2)
#This one might take some time because the each will have to run through every element of two arrays.
sum = []
array1.each_index {|i| sum.push(array1[i] + array2[i]) }
sum
end
end
53 changes: 52 additions & 1 deletion set1/set1.rb
Original file line number Diff line number Diff line change
@@ -1,10 +1,61 @@
module Set1
# I think this method is O(n)
def self.swap_small(array)
if array.length == 1
return array
else
min = array.first
array.each do |n|
if n < min
min = n
end
end
array[array.index(min)] = array.first
array[0] = min
array
end

end
# I think this method is O(n^2)
def self.find_sum_2(array, sum = 0)
if array.include?(sum)
return true
elsif array.empty?
return false
else
array.each_index do |x|
array.each_index do |y|
if array[x] + array[y] == 0
return true
end
end
end
end
false
end

#I think this method is O(n^3)
def self.find_sum_3(array)
if array.include?(0)
return true
elsif array.empty?
return false
else
array.each_index do |x|
array.each_index do |y|
array.each_index do |z|
if array[x] + array[y] + array[z] == 0
return true
end
end
end
end
end
false
end

end