Skip to content

Instantly share code, notes, and snippets.

@dstavis
dstavis / gist:7979221
Created December 15, 2013 22:31
Exercise 6: Triangle side lengths Write a method valid_triangle? which takes as its input three non-negative numbers. It should return true if the three numbers could form the side lengths of a triangle and false otherwise. The arguments don't correspond to specific sides. Don't worry about handling negative inputs — garbage in, garbage out. For…
#Write a method valid_triangle? which takes as its input three non-negative numbers.
def valid_triangle?(a, b, c)
#if the three numbers could form the side lengths of a triangle
if a**2 + b**2 == c**2
#It should return true
return true
#and false otherwise.
else
return false
@dstavis
dstavis / gist:7978900
Last active December 31, 2015 11:19
Exercise 16, Calculating the median of an array of numbers.
def median(array)
array.sort!
#if total number of items in the array is odd,
if array.length % 3 == 0
#Figure out the index of the middle item. Which is one greater than half the length rounded down.
middle_index = array.length / 2 + 1
middle_index = middle_index.to_int
#return the item at that index
median = array[middle_index]
@dstavis
dstavis / gist:7978828
Last active December 31, 2015 11:19
Exercise 17, Socrates
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]