Skip to content
Advertisement

Merge sets when two elements in common

This is the follow up of compare sets

I have

JavaScript

I want to merge the sets when there are two elements in common. For example 0,1,2 and 0,2,6 has two elements in common so merging them to form [0,1,2,6].

Again [0,1,2,6] and [2,6,7] has 2 and 6 common. so merging them and getting [0,1,2,6,7].

The final output should be :

JavaScript

I tried like this :

JavaScript

But the result I got was :

JavaScript

Any idea ? Is there any way to get the desired output?

Advertisement

Answer

Some considerations:

  • Each time you apply a merge, you have to restart the procedure and iterate over the modified collection. Because of this, the iteration order of the input set is important, if you want your code to be deterministic you may want to use collections that give guarantees over their iteration order (e.g. use LinkedHashSet (not HashSet) or List.
  • Your current code has side effects as it modifies the supplied sets when merging. In general I think it helps to abstain from creating side effects whenever possible.

The following code does what you want:

JavaScript

For testing this method I created two helper methods:

JavaScript

These helper methods allow to write very readable tests, for example (using the numbers from the question):

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement