Created
August 8, 2017 22:59
-
-
Save san983/2f0ff1cb8936ba4b15897ab3fb6f90b2 to your computer and use it in GitHub Desktop.
Example of mode implementation for Alex
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
class Example | |
# mode - Just another mode implementation | |
# | |
# @author Santiago Traversa | |
# @param [Array<Integer>] | |
# @example [1,1,2,3,4] #=> 1 | |
# | |
# @raise [ExceptionClass] if param is not an Array | |
# | |
# @return [Integer] The most repeated integer in the initial array | |
def mode(numbers) | |
# Check if numbers is an Array | |
unless numbers.is_a?(Array) | |
raise ArgumentError.new("Only an Array is allowed") | |
end | |
# Check if all the values in they Array are integers | |
unless numbers.all? {|i| i.is_a?(Integer) } | |
raise ArgumentError.new("Only an Array with all integers inside is allowed") | |
end | |
summary = {} | |
# Build a hash counting the times each number appears | |
numbers.each do |x| | |
# if summary[x] | |
# summary[x] += 1 | |
# else | |
# summary[x] = 1 | |
# end | |
# Simple hack to avoid the if statement | |
summary[x] = summary[x].to_i + 1 | |
end | |
# Return the key (actually the number) | |
# of the most repeated number in the array | |
numbers.max_by { |times| summary[times] } | |
end | |
end | |
example = Example.new | |
numbers = [1,2,2,3,4,5,5,99] | |
puts example.mode(numbers) # Returns 2 | |
numbers = [1,2,2,3,4,4,4,5,5,99] | |
puts example.mode(numbers) # Returns 4 | |
numbers = [1,2,2,3,4,4,4,5,5,5,5,99] | |
puts example.mode(numbers) # Returns 5 | |
numbers = [1] | |
puts example.mode(numbers) # Returns 1 | |
numbers = [] | |
puts example.mode(numbers) # Returns nil | |
numbers = nil | |
puts example.mode(numbers) # Returns ArgumentError | |
numbers = [1,:two,3] | |
puts example.mode(numbers) # Returns ArgumentError | |
numbers = [1,'two',3,3] | |
puts example.mode(numbers) # Returns ArgumentError |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment