Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intersection of two dimensional array

Tags:

arrays

ruby

Is there a simple way to find the intersection of a two dimensional array? For example:

arr1 = [1,2,3,4,5]
arr2 = [5,6,7,8]
arr3 = [5]
bigarr = [arr1,arr1,arr3]

I know that it's possible to do:

intersection = arr1 & arr2 & arr3 # => 5
intersection = big_arr[0] & big_arr[1] & big_arr[2] # => 5

but the number of elements in big_arr will vary. I was wondering if there was a simple way to intersect all the elements in big_arr regardless of the number of elements.

like image 422
Cosi Avatar asked Mar 17 '26 04:03

Cosi


1 Answers

Use #reduce like

arr1 = [1,2,3,4,5]
arr2 = [5,6,7,8]
arr3 = [5]
bigarr = [arr1,arr2,arr3]
bigarr.reduce(:&) # => [5]
like image 64
Arup Rakshit Avatar answered Mar 19 '26 02:03

Arup Rakshit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!