0
[ 1, 1, 3, 5 ] & [ 1, 2, 3 ]                 #=> [ 1, 3 ]
[ 'a', 'b', 'b', 'z' ] & [ 'a', 'b', 'c' ]   #=> [ 'a', 'b' ]

I need the intersection of each array with all other arrays within an array.

So the array could look like ->

 a = [[1, 2, 3], [3, 4, 5], [4, 5, 6]]

The result should look like ->

 a = [[3],[3,4,5][4,5]]

Any suggestions?

5
  • Can you please add an example of your expected result? Commented Aug 20, 2016 at 12:50
  • You should still provide an example for other looking at this issue. I did give a solution, but it was by making an educated guess. Commented Aug 20, 2016 at 12:59
  • Data ->> a = [[1, 2, 3], [3, 4, 5], [4, 5, 6]] Extraction via intersection (expected result) ->> a = [[3],[3,4,5][4,5]] thats what i need.. Commented Aug 20, 2016 at 13:02
  • It's not clear to me what needs to be intersected with what - why is [1,2,3] not intersected with [4,5,6] for example. Add any clarifying details to the question itself rather than just as a comment. Commented Aug 21, 2016 at 15:11
  • @FrederickCheung Question mended. The issue is already solved by the answers. Commented Aug 21, 2016 at 17:08

2 Answers 2

2

Look into the combination method.

a = [[1, 2, 3], [3, 4, 5], [4, 5, 6],[1,"a","b"]]

p a.combination(2).map{|x,y| x & y } #=> [[3], [], [1], [4, 5], [], []]

And if you do not want the empty arrays in there:

p a.combination(2).map{|x,y| x & y }.reject(&:empty?) #=> [[3], [1], [4, 5]]

Edit: After seeing some examples what OP actually want here is how I would achieve the desired result:

original = [[1, 2, 3], [3, 4, 5], [4, 5, 6]] 

def intersect_with_rest(array)
  array.size.times.map do
    first, *rest = array
    array.rotate!
    first & rest.flatten
  end
end

p intersect_with_rest(original) #=> [[3], [3, 4, 5], [4, 5]]
p original #=> [[1, 2, 3], [3, 4, 5], [4, 5, 6]]

Or:

original = [[1, 2, 3], [3, 4, 5], [4, 5, 6]] 

result = original.map.with_index do |x,i|
  x & (original[0...i]+original[1+i..-1]).flatten
end

p result #=> [[3], [3, 4, 5], [4, 5]]
Sign up to request clarification or add additional context in comments.

Comments

0

Yeah, finally I found a solution. Maybe there is a simpler way, but that works for me now..

c = [[1,2,3],[3,4,5],[4,5,6]]
results = [];c.length.times.each {|e| results.push c.rotate(e).combination(2).map {|x, y| x & y}}
results.map{|x, y| y + x}

=> [[3], [3, 4, 5], [4, 5]] 

Thanks to @hirolau for the hint. Best regards

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.