Skip to content

Instantly share code, notes, and snippets.

@suminb
Created August 28, 2012 07:53
Show Gist options
  • Save suminb/3495984 to your computer and use it in GitHub Desktop.
Save suminb/3495984 to your computer and use it in GitHub Desktop.
Ruby Programming Exercise
unsorted_list = [5, 8, 1, 2, 4, 9, 7, 6, 3]
sorted_list1 = [2, 3, 5, 7, 11, 13, 17, 19]
sorted_list2 = [2, 4, 8, 10, 12, 14, 16, 18]
def min(list)
# Google for 'ruby ternary operator'
return list.reduce { |x, y| x < y ? x : y }
end
def max(list)
# Fill out here
end
def sum(list)
# Fill out here
end
def filter(list, f)
return list.find_all { |x| f.call(x) }
end
def sumif(list, f)
# Fill out here
end
# You may assume list1 and list2 have the same number of elements
def merge(list1, list2)
# Fill out here
end
# This should print '1'
puts min(unsorted_list)
# This should print '9'
puts max(unsorted_list)
# This should print '45'
puts sum(unsorted_list)
# This should print '77'
puts sum(sorted_list1)
# This should print '84'
puts sum(sorted_list2)
# This should print out '[11, 13, 17, 19, 23]'
puts filter(sorted_list1, lambda { |x| x > 10 }).inspect()
# This should print out '[12, 14, 16, 18]'
puts filter(sorted_list2, lambda { |x| x > 10 }).inspect()
# This should print '17'
puts sumif(sorted_list1, lambda { |x| x < 10 }).inspect()
# This should print '25'
puts sumif(unsorted_list, lambda { |x| x % 2 == 1 }).inspect()
# This should print out '[2, 2, 3, 4, 5, 8, 7, 10, 11, 12, 13, 14, 16, 17, 18, 19]'
puts merge(sorted_list1, sorted_list2).inspect()
@suminb
Copy link
Author

suminb commented Aug 28, 2012

Expected output:

$ ruby exercise.rb 
1
9
45
77
84
[11, 13, 17, 19]
[12, 14, 16, 18]
17
25
[2, 2, 3, 4, 5, 8, 7, 10, 11, 12, 13, 14, 16, 17, 18, 19]

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