Detect if 2 ranges share elements

D

Derek Cannon

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
 
I

Intransition

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 =A0[9..15] =3D> false (they share common elements)
[1..10] and [11..20] =3D> true (they are both unique)

Checkout Facets' Range#overlap
=3D> false
 
J

Jean-Julien Fleck

Hello Derek

2010/4/11 Derek Cannon said:
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 =3D r1.to_a & r2.to_a
!arr.empty?
end

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

Cheers,

--=20
JJ Fleck
PCSI1 Lyc=E9e Kl=E9ber
 
D

Derek Cannon

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

Any ideas why?
 
D

Derek Cannon

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 method `overlap?' for [1..8]:Array (NoMethodError)
 
D

Derek Cannon

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,158
Messages
2,570,881
Members
47,414
Latest member
djangoframe

Latest Threads

Top