Detect if 2 ranges share elements

Probably a simple problem for most of you out there:

What is the best way to make sure two ranges don’t share any elements?

For example:

[1…10] and [9…15] => false (they share common elements)
[1…10] and [11…20] => true (they are both unique)

Thanks,
Derek

On Apr 10, 7:13 pm, Derek C. [email protected] wrote:

Probably a simple problem for most of you out there:

What is the best way to make sure two ranges don’t share any elements?

For example:

[1…10] and [9…15] => false (they share common elements)
[1…10] and [11…20] => true (they are both unique)

Checkout Facets’ Range#overlap

require ‘facets/range/overlap’
=> true

(1…10).overlap?(9…15)
=> true

(1…10).overlap?(11…20)
=> false

Hello Derek

2010/4/11 Derek C. [email protected]:

Probably a simple problem for most of you out there:

What is the best way to make sure two ranges don’t share any elements?

I don’t know if it’s the best but it should be working at least

def have_common?(r1,r2)
arr = r1.to_a & r2.to_a
!arr.empty?
end

have_common?(1…10,9…15)
have_common?(1…10,11…20)

Cheers,

Ah, nevermind:

gem install facets
…it could save your life.

Thanks Jean, very elegant solution!

Thomas, I like your solution but I get

in `require’: no such file to load – facets/range/overlap (LoadError)

when I try to use

require ‘facets/range/overlap’

Any ideas why?

Ok, I’m way too tired to be given posting privileges… Used [] instead
of (). I shall go far, far away now.

And I’m back again…

Facets is no longer giving me a “not found” error, but when I do the
following:

require ‘facets/range/overlap’
puts [1…8].overlap?([7…14])

I get:

in <main>': undefined methodoverlap?’ for [1…8]:Array (NoMethodError)

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs