title: Merge sub arrays containing that have intersection in Groovy / Java
body: <p>Suppose we have one array:</p>
  
  <pre><code>def a = [[0], [1], [2], [2, 1], [1, 2], [3, 2], [2, 3], [3], 
          [4, 3], [3, 4], [4], [5], [6], [8], [10, 7], [7, 10], 
          [7, 8], [8, 7], [9], [10], [7, 10, 8], [8, 9], [9, 8], 
          [11, 0], [0, 11]]
  </code></pre>
  
  <p>then</p>
  
  <p><code>def b = reduce(a)</code></p>
  
  <p>should produce </p>
  
  <pre><code>[ [0, 11], [1, 2, 3, 4], [5], [6], [7,8,9,10] ]
  </code></pre>
  
  <p>My logic was to have a new array <code>reducedObjects</code> that would contain the result. First subarray from <code>objects</code> is copied to <code>reducedObjects</code> and then next subarray is checked if has intersection with subarrays from <code>reducedObjects</code>. If there is an intersection, then make a union from the subarray in <code>reducedObjects</code> and the original subarray.</p>
  
  <pre><code>def reduce(objects) {
      def reducedObjects = new ArrayList()
      objects.each { object -&gt;
          if (reducedObjects.size() == 0) {
              reducedObjects &lt;&lt; object
          } else {
              def isReduced = false
              for (int i = 0; i &lt; reducedObjects.size(); i++) {
  
                  def equals = false
                  object.each { it -&gt;
                      if(reducedObjects[i].contains(it)) {
                          equals = true
                          isReduced = true
                      }
                  }
                  if (equals) {
                      reducedObjects[i] = (object + reducedObjects[i]).unique().sort()
                      reducedObjects.unique()
                  }
  
              }
              if(!isReduced) {
                  reducedObjects &lt;&lt; object
              }
          }
      }
      return reducedObjects.unique()
  }
  </code></pre>
  
  <p>The following function do not work fine, as the result is:</p>
  
  <pre><code>[[0, 11], [1, 2, 3, 4], [5], [6], [7, 8, 9, 10], [8, 9]]
  </code></pre>
  
  <p>The problem is that <code>reducedObjects</code> has an subarray <code>[7, 8]</code> and then the next subarray is <code>[9]</code>.  The function will create a new subarray as there is no intersection, but in next iteration, there is a subarray [8, 9] and it is merged in both <code>[7,8]</code> and <code>[9]</code>.</p>
  
  <p>Is there any better solution to do this? Or somehow to improve this solution?</p>