Skip to content

Instantly share code, notes, and snippets.

@nimamehanian
Created February 21, 2013 02:38
Show Gist options
  • Save nimamehanian/5001541 to your computer and use it in GitHub Desktop.
Save nimamehanian/5001541 to your computer and use it in GitHub Desktop.
Display how many times an integer occurs at each index, within a nested array.
def countem(list_of_lists)
occurrences = {}
list_of_lists.each do |inner_list|
inner_list.each_with_index do |integer, index_of_integer|
if occurrences.has_key?("#{integer} @ #{index_of_integer}") == false
# if not there, add it
occurrences["#{integer} @ #{index_of_integer}"] = 1
else
# if there, increment
occurrences["#{integer} @ #{index_of_integer}"] += 1
end
end
end
occurrences.each_pair do |key, value|
p "#{key} -> #{value}"
end
end
# Uncomment for testing
# countem([ [1, 2, 3], [3, 3, 4], [1, 3, 1], [1, 3, 4, 2, 1] ])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment