What would be the best way to merge arrays nested in an array that shares at least an element ? Here's an example:
some_method([[1, 2], [2, 3], [4, 5]])
#=> [[1, 2, 3], [4, 5]]
some_method([[1, 2], [2, 3], [3, 4], [5,6]])
#=> [[1, 2, 3, 4], [5, 6]]
What would be the best way to merge arrays nested in an array that shares at least an element ? Here's an example:
some_method([[1, 2], [2, 3], [4, 5]])
#=> [[1, 2, 3], [4, 5]]
some_method([[1, 2], [2, 3], [3, 4], [5,6]])
#=> [[1, 2, 3, 4], [5, 6]]
Here's a very simple approach. The steps are as follows.
Beginning with an array
a = arr.map(&:uniq)
,arr
being the initial array of arrays, look for two arrays ofa
that share an element, among all combinations of two arrays ofa
. If none are found, returna
(fini!); else go to step 2.If
a[i]
anda[j]
are found to contain a common element,a[i]
becomesa[i].concat(a[j]).uniq
anda[j]
is deleted.Repeat #1.
or, more expressive:
the most precise solution, that works for any permutations, but consumes more time:
It's a little verbose, but here is a recursive method that solves the problem properly:
This will keep re-iterating through the list, so the order of inputs is irrelevant.
This would work:
Examples:
I'm using a hash
h
to store the array that correspond to a given element. The hash returns[]
if a key doesn't exist.After inserting
[1, 2]
, the hash looks like this:When inserting
[2, 3]
, the arrays for2
and3
are fetched via:then
[2, 3]
itself is added:and everything is
|
-ed:This result is stored in
tmp
. It becomes the new value for the contained keys:Which is equivalent to:
Afterwards,
h
looks like this:At the end, the distinct values are returned via
h.values | h.values
.