Last active
February 15, 2018 07:42
-
-
Save haroldofurtado/8f029bba6169c4b35b8738aba2ecab80 to your computer and use it in GitHub Desktop.
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
array = Array.new(10000) { rand(1...5000) } | |
def most_popular_number(array) | |
a = array.uniq.map { |e| [e, array.count(e)] }.sort_by { |_, cnt| -cnt } | |
elements = a.take_while { |_, cnt| cnt == a.first.last }.sort | |
# Verify if the array is empty. | |
if array.empty? | |
puts 'MostPopularNumber array is empty!' | |
# Verify if there's only one element. | |
elsif array.size == 1 | |
puts "MostPopularNumber (#{array}, #{array.size}) --> #{a.first.first} // #{a.first.first} is the only number" | |
elsif elements.count == 1 | |
puts "MostPopularNumber (#{array}, #{array.size}) --> #{a.first.first} // #{a.first.first} appears #{a.first.last} times" | |
elsif elements.sort.count >= 2 | |
puts "MostPopularNumber (#{array}, #{array.size}) --> #{a.first.first} // #{a.first.first} < #{a[1].first}" | |
end | |
end | |
most_popular_number(array) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment