简体   繁体   中英

Cleanest way to count common elements by nested array pairs

I have two nested arrays:

one = [
  ["Hiking", "fishing", "photography"], 
  ["The Avengers", "The Dark Knight", "Lord of the Rings"], 
  ["Firefly", "Battlestar Galactica", "The Expanse"], 
  ["The Hobbit", "1984", "Dune", "Ender's Game"]
]
two = [
  ["Hiking", "photography"], 
  ["Whiplash", "Pulp Ficiton", "The Avengers"], 
  ["Firefly", "Battlestar Galactica", "The Expanse"], 
  ["The Hobbit", "1984", "Dune", "Ender's Game"]
]

I guess I can iterate and compare one by one, but is there a better way?

I would do something like:

(one.flatten & two.flatten).size
#=> 10

Possible solution (assuming you want to find common elements by arrays pairs):

one.zip(two).flat_map { |f, s| f & s }.count
#=> 10

You might consider the following to avoid the creation of the temporary array one.zip(two) .

one.size.times.reduce(0) { |t,i| t + (one[i] & two[i]).size }
  #=> 10

Just one more way to skin a cat

one.each_with_index.inject(0){|memo,(a,i)| memo += (a & two[i]).size }
#=> 10

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