Created
June 19, 2012 14:32
-
-
Save thorn/2954530 to your computer and use it in GitHub Desktop.
Revisions
-
thorn created this gist
Jun 19, 2012 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,30 @@ 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 This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,34 @@ 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