Skip to content

Instantly share code, notes, and snippets.

@RoxasShadow
Created May 14, 2013 14:04
Show Gist options
  • Save RoxasShadow/5576146 to your computer and use it in GitHub Desktop.
Save RoxasShadow/5576146 to your computer and use it in GitHub Desktop.
class Array
def most_popular(n = 1)
get_occurrency_hash[n * -1].first
end
def occurrences(n = 1)
get_occurrency_hash[n * -1].last
end
def has_duplicates?
get_occurrency_hash.last.last > 1
end
def has_triplicates?
get_occurrency_hash.last.last > 2
end
protected
def get_occurrency_hash
Hash.new(0).tap { |h|
self.each { |e| h[e] += 1 }
}.sort_by { |k, v| v }
end
end
ary = (0...9).map{(65+rand(26)).chr} # [1, 2, 1, 2, 1]#
if ary.has_triplicates?
puts "In #{ary} the second most popular element is \"#{ary.most_popular 2}\" (#{ary.occurrences 2} times)."
elsif ary.has_duplicates?
puts "In #{ary} the most popular element is \"#{ary.most_popular}\" (#{ary.occurrences} times)."
else
puts "#{ary} has not duplicate elements."
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment