Say I have a 2D array like so:
[ [0, 1], [2, 3], [0, 4] ]
How can I use intersection or union of those arros above to get the result of:
[[0, 1, 4], [2, 3]]
To explain the above:
- The reason for
[0, 1, 4]
is because 0 is connected to 1 and 4 - The reason for
[2,3]
is because 2 is only connected to 3
How can we do this using set intersection or union? I'm pretty its possible.
Code
My current implementation is actually creating Node
and looking for neighbours:
def connected_neighbors(astronaut)
graph, to_return, node_a, node_b = {}, [], nil, nil
astronaut.each do |city_a, city_b|
node_a, node_b = (graph[city_a] || Node.new(city_a)), (graph[city_b] || Node.new(city_b))
node_a.connect node_b
graph[city_a] = node_a unless graph[city_a]
end
graph.each do |key,_|
node = graph[key]
to_return << [node.key, node.neighbors.collect(&:key)].flatten
end
to_return
end
The above implementation will output the expected result as above, but not for most other cases.
Update
For case [1, 2], [2, 3]
The output should be [[0], [1,2,3]]
This is because of the range in the array is from 0 to 3.
So because 0 doesn't exist in the array, it will be separate
If I understand what you are asking for, maybe you can group:
In case of
astr = [ [0, 1], [1, 3], [3, 4], [2, 5], [5, 0] ]
, it returnsIn case of
astr = [ [1, 2], [2, 3] ]
, it returnsFeel free to
.unshift [0]
in case result size is 1 or less.