derek
1
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
derek
2
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
derek
3
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,
derek
5
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?
derek
6
Ok, I’m way too tired to be given posting privileges… Used [] instead
of (). I shall go far, far away now.
derek
7
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)