Skip to content

Instantly share code, notes, and snippets.

@thorn
Created June 19, 2012 14:32
Show Gist options
  • Save thorn/2954530 to your computer and use it in GitHub Desktop.
Save thorn/2954530 to your computer and use it in GitHub Desktop.
grouper and unit test
class Grouper
def self.group(list)
result = list.inject([]) do |res, gr1|
current_group = recursive_finder(list, gr1)
res << current_group
end
result | list
end
def self.recursive_finder(list, group)
current_group = group
list.each do |gr2|
if similar? current_group, gr2
list.delete group
list.delete gr2
current_group |= gr2 | recursive_finder(list, gr2)
end
end
current_group
end
def self.similar?(list1, list2)
for el in list1
return true if list2.include?(el)
end
false
end
end
require_relative "../lib/grouper"
describe Grouper do
before(:each) do
@list = [[1,2],[2,6],[3],[4,5],[5,1]]
end
it "should return true if two arrays have similar element" do
list1 = [1,2,3]
list2 = [3,4,5]
Grouper.similar?(list1, list2).should be true
end
it "should return false if there are no common element" do
list1 = [1,2,3]
list2 = [4,5,5]
Grouper.similar?(list1, list2).should be false
end
it "should return the list of groups" do
Grouper.group(@list).should == [[1,2,6,5,4],[3]]
end
it "should return identical array when there are no common elements" do
list2 = [[1,2],[3,4],[5,6]]
Grouper.group(list2).should == [[1,2],[5,6],[3,4]]
end
it "should return exact 1 array in array when all elements are common" do
list2 = [[1,2],[2,1]]
Grouper.group(list2).should == [[1,2]]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment