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.

Revisions

  1. thorn created this gist Jun 19, 2012.
    30 changes: 30 additions & 0 deletions grouper.rb
    Original 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
    34 changes: 34 additions & 0 deletions grouper_spec.rb
    Original 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