diff --git a/array_problems/arrays.rb b/array_problems/arrays.rb index 7a4a2cc..9037f27 100644 --- a/array_problems/arrays.rb +++ b/array_problems/arrays.rb @@ -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 diff --git a/set1/set1.rb b/set1/set1.rb index 0ca2970..8811706 100644 --- a/set1/set1.rb +++ b/set1/set1.rb @@ -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 + + + + +