3

I need to make intersection of n-arrays with millions of elements (database ID's). This code works perfect, but slow (with very big arrays). How can i improve it?

[[1,2,3,4],[2,4,6,8],[4,5,8]].inject([]){|c,v| c = v if c.size==0; c = c&v if c.size>0; c } 

2 Answers 2

6
[1,2,3,4] & [2,4,6,8] & [4,5,8] #=> [4] 

The intersection method uses hash so it should be quick.

Sign up to request clarification or add additional context in comments.

Comments

3

Ruby provides an intersection opperator.

May I suggest you try this:

> [[1,2,3,4],[2,4,6,8],[4,5,8]].reduce{ |accum, arr| accum & arr } => [4] 

Edit:

This can be written a little more concise but it suffers from readability.

[[1,2,3,4],[2,4,6,8],[4,5,8]].reduce(:&) 

5 Comments

yes. [[1,2,3,4],[2,4,6,8],[4,5,8]].reduce{ |accum, arr| accum | arr }
You can use without &, just reduce(:&)
It's not a reduce, it's because of intersection method.
Correct. It would work the same if you replace reduce with inject as they are aliases of each other.
What is the time complexity of this operator? Any links will help

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.