简体   繁体   中英

How to compare arrays inside an array with each other in ruby?

[ 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?

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]]

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM