Part 2 of my Ruby retrospective discussing my progress through The Odin Project!
Link to part 1.
Stock Picker
Another relatively simple project, this time my first project to make my own method calls within another method. Looking back this solution doesn’t particularly scale very well over a larger amount of data points, each new value in the array causes the program to iterate through the rest of the array. I’m not sure how to optimize this to be less intensive so any ideas would be very helpful here.
Original code:
def stock_picker ( price_array ) i = 0 lowest_day = 0 greatest_difference = 0 while i < price_array . length - 1 difference = find_highest_difference ( price_array , i ) if difference > greatest_difference greatest_difference = difference end i += 1 end puts greatest_difference end def find_highest_difference ( previous_array , place_in_array ) highest_difference = 0 while place_in_array < previous_array . length i = place_in_array + 1 while i < previous_array . length if previous_array [ i ] - previous_array [ place_in_array ] > highest_difference highest_difference = previous_array [ i ] - previous_array [ place_in_array ] end i += 1 end place_in_array += 1 end return highest_difference end
With some easy ruby fixes:
def stock_picker ( price_array ) i = 0 greatest_difference = 0 while i < price_array . length - 1 difference = find_highest_difference ( price_array , i ) if difference > greatest_difference greatest_difference = difference end i += 1 end greatest_difference end def find_highest_difference ( previous_array , place_in_array ) highest_difference = 0 while place_in_array < previous_array . length i = place_in_array + 1 while i < previous_array . length if previous_array [ i ] - previous_array [ place_in_array ] > highest_difference highest_difference = previous_array [ i ] - previous_array [ place_in_array ] end i += 1 end place_in_array += 1 end highest_difference end