Skip to content
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
45 changes: 44 additions & 1 deletion lib/possible_bipartition.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,47 @@
require "set"

def possible_bipartition(dislikes)
raise NotImplementedError, "possible_bipartition isn't implemented yet"
if dislikes.empty?
return true
end

dogz = Set.new()
doggos = Set.new()
Comment on lines +8 to +9

Choose a reason for hiding this comment

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

Nice use of a Set.


i = 0
return bipartition_helper(i, dislikes, dogz, doggos)
end

def bipartition_helper(i, dislikes, dogz, doggos)
while i < dislikes.length
dislike = dislikes[i]
if !dogz.include?(i) && !doggos.include?(i)
dogz1 = dogz.clone()
doggos1 = doggos.clone()

dogz1.add(i)
doggos.add(i)

return bipartition_helper(i, dislikes, dogz1, doggos1) || bipartition_helper(i, dislikes, dogz, doggos)

Choose a reason for hiding this comment

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

Originally seeing this pair of recursive calls in this method set off alarm bells, but then I traced through and it doesn't actually make many more recursive calls, it's just a little different from my solution. It does however mean you have do the nested if-else blocks below.

I instead assigned the current "color" for the current node and assigned it's neighbors the alternating color, and then continue in a depth-first-search, and I repeat until the stack is empty. If they already have an incompatible color I return false. This results in a bit simpler code.

This does work however and work well.

elsif dogz.include?(i)
dislike.each { |dog|
if dogz.include?(dog)
return false
else
doggos.add(dog)
end
}
elsif doggos.include?(i)
dislike.each { |dog|
if doggos.include?(dog)
return false
else
dogz.add(dog)
end
}
end

i += 1
end
return true
end