Skip to content

Instantly share code, notes, and snippets.

@kimyoutora
Created February 9, 2012 22:23
Show Gist options
  • Save kimyoutora/1783830 to your computer and use it in GitHub Desktop.
Save kimyoutora/1783830 to your computer and use it in GitHub Desktop.
Count occurrences in sorted array
def occurrences(sorted_array)
puts "occurrences: #{sorted_array.inspect}"
count = 0
sorted_array.each_with_index do |num, index|
if index + 1 >= sorted_array.size || num != sorted_array[index+1]
puts "#{num}: #{count+1}"
count = 0
else
count += 1
end
end
end
array = 10.times.map { rand(10) }.sort
occurrences(array)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment