Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
notes from class
# hopefully the descriptive names eliminate the need for comment
def search(collection, the_item_for_which_i_am_searching, the_lower_bounds=0, the_upper_bounds=collection.length)
the_middle_index = (the_lower_bounds + the_upper_bounds) / 2
the_middle_item = collection[the_middle_index]
return the_middle_index if the_middle_item == the_item_for_which_i_am_searching
return -1 if the_upper_bounds <= the_lower_bounds
if the_item_for_which_i_am_searching < the_middle_item
return search( collection, the_item_for_which_i_am_searching, the_lower_bounds, the_middle_index-1 )
else
return search( collection, the_item_for_which_i_am_searching, the_middle_index+1, the_upper_bounds )
end
end
# bad variable names; for contrast
#
# def search(ary, i, l=0, r=ary.length)
# mid = (l + r) / 2
# return mid if ary[mid] == i
# return -1 if r <= l
# return i < ary[mid] ? search( ary, i, l, mid-1 ) : search( ary, i, mid+1, r )
# end
p search([1,2,3,5,6,7,8], 4) == -1
p search([1,2,3,5,6,7,8], 0) == -1
p search([1,2,3,5,6,7,8], 9) == -1
p search([1,2,3,5,6,7,8], 6) == 4
# - first pass comments
## - second pass comments
def prime_factors number, factors=[] # solving for 21
# given line 25/33, number may eventually equal one
# since a number divided by itself is 1, aka prime
return factors if number == 1
# starting from 2, finds the next factor in a range
# from 2 to the number we are finding factors for
# in this case, next factor is the prime # 3
next_factor = (2..number).find do |possible_factor| # the first factor found will be prime
number % possible_factor == 0
end
# save the factor, 3
factors << next_factor
## the second time through, 7 gets put here too
#finds the opposing factor ie: 21= 3 * 7
# our method will find 3, next attemp will be
# to factor down 7, if we can
next_attempt = number / next_factor
## 7/7 is 1; we will hit our base case at the
## beginning of our 3rd time through
# we pass in our collection of factors,
# if it is prime, we will return the factors
# array which we have been collecting
# throughout the stack
prime_factors( next_attempt , factors )
end
p prime_factors 21
module Enumerable
def my_each
for i in self
yield(i)
end
end
def my_reduce(*args, &my_block)
arg_count = args.length
if !block_given?
if arg_count == 1
operator, init_value = args.first, self.first
elsif arg_count == 2
init_value, operator = args
end
self.my_each do |i|
init_value = eval("init_value #{operator} #{i}")
end
return init_value
end
if block_given?
if arg_count == 0
init_value = self.first
elsif arg_count == 1
init_value = args.first
end
self.my_each do |i|
init_value = my_block.call(init_value, i)
end
return init_value
end
end
end
p [*1..5].my_reduce(0) {|sum, i| sum + i}
p (1..5).my_reduce(0, :+)
p (1..5).my_reduce(:+)
p (1..5).my_reduce(:*)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment