0

I have an array (or possibly a set) of integers (potentially non sequential but all unique) and a range of (sequential) numbers. If I wanted to check if any of the numbers in the range existed in the array, what would be the most efficient way of doing this?

array = [1, 2, 5, 6, 7]
range = 3..5

I could iterate over the range and check if the array include? each element but this seems wasteful and both the array and the range could easily be quite large.

Are there any methods I could use to do some sort of array.include_any?(range), or should I look for efficient search algorithms?

3 Answers 3

3

I would do

(array & range.to_a).present?

or

array.any? { |element| range.cover?(element) }

I would choose a version depending on the size of the range. If the range is small that the first version is probably faster, because it creates the intersection once and doesn't need to check cover for every single element in the array. Whereas if the range is huge (but the array is small) the second version might be faster, because a few comparisons might be faster that generating an array out of a huge range and building the intersection.

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

4 Comments

I really like the first method, would you mind explaining what the single & does? also, could you put the link to the documentation to .present? or at least explain a little as to how it works/is used?
& is the intersection, it returns a new array containing elements common to the two arrays: [1, 2, 3] & [2, 3, 4] #=> [2, 3]. present? is the opposite to nil? || empty?
@Promethean_Sin present? is not a Ruby's method. It is Rails'.
I actually DID mention rails in the title @sawa. Thanks for the grammar check =0]
1
([1, 2, 5, 6, 7] & (3..5).to_a).any?
# => true

Comments

0

Don't need no stinkin' &:

array.uniq.size + range.size > (array + range.to_a).uniq.size

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.