Skip to content

Instantly share code, notes, and snippets.

@yoshprogrammer
Last active August 29, 2015 14:01
Show Gist options
  • Save yoshprogrammer/b723acc90d6e1fec507e to your computer and use it in GitHub Desktop.
Save yoshprogrammer/b723acc90d6e1fec507e to your computer and use it in GitHub Desktop.
Exercise_36
def max(list)
max_so_far = list.first
for item in list
if item > max_so_far
max_so_far = item
end
end
return max_so_far
end
def count_in_list(list, item_to_count)
running_total = 0
for item in list
if item == item_to_count then
running_total = running_total + 1
end
end
running_total
end
def count_max(list)
running_total = 0
for item in list
if item == max(list) then
running_total = running_total + 1
end
end
running_total
end
count_max([10, 1,2,10,10]) == 3
# You can write this in a single line using nothing more than
# the max and count_in_list methods that you've already written.
# Question 1: I understand that I need to have the result of max(list) = item_to_count. I just do not get how I would
# implement the result of one method as one of the arguments for the next method in a single line. I'm a little lost on this one.
# I also need the max(list) to run first in order for the item_to_count to have the input it needs. I just haven't been able
# to figure out how to make that happen in one line.
@jfarmer
Copy link

jfarmer commented May 27, 2014

I'll put one solution here and I'd like you to ponder it for a bit to see if it clicks.

def count_max(list)
  count_in_list(list, max(list))
end

If the fact that this is "all in one line" is throwing you off, we could also write

def count_max(list)
  list_max = max(list)
  count_in_list(list, list_max)
end

but the variable assignment list_max = max(list) is superfluous. We can pass the return value of max(list) directly into the argument list of count_in_list.

Since you have a STEM background, consider these scenarios:

def add(x,y)
  x + y
end

def multiply(x, y)
  x * y
end

# This is equivalent to the "mathy" function f(x) = x^2
def square(x)
  multiply(x,x)
end

# This is equivalent to the "mathy" function f(x) = x^2 + 1
def square_plus_one(x)
  add(multiply(x,x), 1)
end

# Likewise, we could write
def square_plus_one(x)
  x*x + 1
end

# since multiply(x,x) == x*x for any number x and add(y,1) == y + 1 for any number y

@yoshprogrammer
Copy link
Author

That makes a lot of sense.

We're basically having max(list) as one of the arguments which performs the function of it replacing item_to_count in my original code as the highest number.

With that the function runs through the list, having the largest value selected as item_to_count through the predefined method of max(list).

That clears up a lot thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment