Skip to content

Instantly share code, notes, and snippets.

@jkaihsu
jkaihsu / longest_string.rb
Created March 7, 2013 08:17
Write a method longest_string which takes as its input an Array of Strings and returns the longest String in the Array. For example: # 'zzzzzzz' is 7 characters long longest_string(['cat', 'zzzzzzz', 'apples']) # => "zzzzzzz" If the input Array is empty longest_string should return nil.
def longest_string(array)
if array.empty?
nil
else
long_string = array.group_by(&:size).max.last
long_string[0]
end
end
@jkaihsu
jkaihsu / mode.rb
Created March 7, 2013 08:16
Write a method mode which takes an Array of numbers as its input and returns an Array of the most frequent values. If there's only one most-frequent value, it returns a single-element Array. For example, mode([1,2,3,3]) # => [3] mode([4.5, 0, 0]) # => [0] mode([1.5, -1, 1, 1.5]) # => [1.5] mode([1,1,2,2]) # => [1,2] mode([1,2,3]) # => [1,2,3], b…
def mode(array)
mode = array.inject(Hash.new(0)) { |h,v| h[v] = h[v] + 1; h}
mode.select{ |h,v| v == mode.values.max }.keys
end
@jkaihsu
jkaihsu / count_bwtn.rb
Created March 7, 2013 08:15
Write a method count_between which takes three arguments as input: An Array of integers An integer lower bound An integer upper bound count_between should return the number of integers in the Array between the two bounds, including the bounds It should return 0 if the Array is empty.
def count_between(array, lower_bound, upper_bound)
array.count{|x| x >= lower_bound && x <= upper_bound}
end
@jkaihsu
jkaihsu / arithmetic.rb
Created March 7, 2013 08:13
Define four methods which correspond to the four basic arithmetic operations: add, subtract, multiply, divide.They should accept either integers or floating point numbers as input. divide should perform floating point division.
def add(x,y)
x + y
end
def subtract(x,y)
x - y
end
def multiply(x,y)
x * y