I have a hash in ruby that looks like this:
[
{"video_id": 3,"tag_id": 2},
{"video_id": 3, "tag_id": 4},
{"video_id": 3, "tag_id": 8},
{"video_id": 5, "tag_id": 2},
{"video_id": 5, "tag_id": 9}
]
And I want it broken up into an array the tag_id's that are common to all the video_id's present. In above case, the array would be:
common_tags[0] = 2
because tag_id number 2 is the only tag that is common to both video_id's 3 and 5.
People succeed in answering ParagramStudios's questions 26% of the time (9 successes in 34 attempts).
Answers by: Rich Collins
That actually looks like a python, not ruby array. In any case here is the solution in Ruby:
video_map_array = [{"videoid" => 3, "tagid" => 2}, {"videoid" => 3, "tagid" => 4}, {"videoid" => 3, "tagid" => 8}, {"videoid" => 5, "tagid" => 2}, {"videoid" => 5, "tagid" => 9}]
all_video_ids = []
#create a map of tagids to videoid arrays
tag_to_video_map = video_map_array.inject({}) do |ttvm, id_map|
all_video_ids << id_map["videoid"] unless all_video_ids.include?(id_map["videoid"])
ttvm[id_map["tagid"]] = [] unless ttvm[id_map["tagid"]]
ttvm[id_map["tagid"]] << id_map["videoid"]
ttvm
end
common_tags = tag_to_video_map.map { |tagid, videoids| tagid if videoids.size == all_video_ids.size }.compact
I'm not sure if I'll try this because my friend joge just gave an alternate solution that works for me. But I'll give you the reward because I trust that this works.
Here is my friend's solution:
videoids = Array.new
common_tags = Array.new
tag_video_tree = Hash.new
tags.each do |video_tag_pair|
videoids << video_tag_pair["video_id"] if not videoids.include?(video_tag_pair["video_id"])
tag_video_tree[video_tag_pair["tag_id"]] = Array.new if not tag_video_tree.has_key?(video_tag_pair["tag_id"])
tag_video_tree[video_tag_pair["tag_id"]] << video_tag_pair["video_id"]
end
tag_video_tree.each_pair do |key, value|
common_tags << key if (videoids - value).empty?
end
Pretty much the same solution but he named his keys wrong (should be videoid not video_id) so it won't work :P
actually i changed it to have the underscores. i had accidently left out the underscores when posting the question here