Last active
December 14, 2015 06:09
-
-
Save astamm78/5040932 to your computer and use it in GitHub Desktop.
Exercise: Calculating the array mode
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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], because all occur with equal frequency | |
def mode(array) | |
result = [] | |
ordered = array.sort | |
new_array = ordered.sort_by { |var| (ordered.rindex(var)) - (ordered.index(var)) } | |
array_last = new_array.last | |
new_array.each do |var| | |
if (ordered.rindex(var) - ordered.index(var)) == (ordered.rindex(array_last) - ordered.index(array_last)) | |
result.push(var) | |
end | |
end | |
result.uniq | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment