Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FIRE - Tram #3

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 37 additions & 2 deletions lib/possible_bipartition.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,39 @@

# Time complexity:O(n) - visiting each node in the graph once, searching in sets is O(1)
# Space complexity: O(n) - the sets can be filled up based on the content of the dislikes
require 'set'
def possible_bipartition(dislikes)
Comment on lines +1 to 4

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍 For time complexity you're also checking every edge for every node so this is O(N + E)

raise NotImplementedError, "possible_bipartition isn't implemented yet"
return true if dislikes.empty?
group_a, group_b, blocked_a, blocked_b = Set.new, Set.new, Set.new, Set.new

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I like the uses of Set


# if this index is not included in blocked_a, and go to the index in the adjacency list, and check if its dislikes are in not in group_a
# check if this index is not included in blocked_b, proceed
# go to the index and check if its dislikes are not in group_b
# return false if all four checks failed
queue = [ 0 ]
queue << 1 if dislikes[0].empty?

until queue.empty?

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a good BFS implementation.

puppy = queue.shift
if !blocked_a.include?(puppy) && group_a.intersection(dislikes[puppy]).empty?
# add puppy to group_a
group_a << puppy
# add it's dislikes to blocked_a
dislikes[puppy].each { |dislike| blocked_a << dislike }
elsif !blocked_b.include?(puppy) && group_b.intersection(dislikes[puppy]).empty?
group_b << puppy
dislikes[puppy].each { |dislike| blocked_b << dislike }
else
return false
end

# place each of puppy's dislikes into queue if they're not in group_a or group_b
# if they're in group_a or group_b, it means that node has been visted
dislikes[puppy].each do |dislike|
if !(group_a + group_b).include?(dislike)
queue << dislike
end
end
end

true
end