I used once cover? and again include?. Both are looking same as per
functionality. But is there any advantages one over the other? or both
are same?
ranges =[(1…10), (60…80), (200…400)]
numbers = [123, 700, 567]
numbers.any?{|x| ranges.any? {|y| y.include? x}} #=> false
numbers = [123, 400, 567]
numbers.any?{|x| ranges.any? {|y| y.include? x}} #=> true
ranges =[(1…10), (60…80), (200…400)]
numbers = [123, 700, 567]
numbers.any?{|x| ranges.any? {|y| y.cover? x}} #=> false
numbers = [123, 400, 567]
numbers.any?{|x| ranges.any? {|y| y.cover? x}} #=> true
I’d expect cover to perform better in a benchmark, since it checks the
min-max rather than the entire range.
On Tue, Apr 30, 2013 at 11:17 PM, Joel P. [email protected]
wrote:
I’d expect cover to perform better in a benchmark, since it checks the
min-max rather than the entire range.
–
Posted via http://www.ruby-forum.com/.
Humm…
irb(main):010:0> require ‘benchmark’
=> true
irb(main):011:0> Benchmark.bm do |x|
irb(main):012:1* x.report(‘include’) { 10000000.times {
(0…99).include?(rand(1000))}}
irb(main):013:1> x.report(‘cover’) { 10000000.times {
(0…99).cover?(rand(1000))}}
irb(main):014:1> end
user system total real
include 5.790000 0.000000 5.790000 ( 5.802889)
cover 5.830000 0.000000 5.830000 ( 5.826916)
Hope this helps… but maybe my benchmark is not accurate as it should
be?
e.
On 04/30/2013 02:58 PM, Edoardo R. wrote:
irb(main):010:0> require ‘benchmark’
Hope this helps… but maybe my benchmark is not accurate as it should be?
e.
Both methods use the start/end of the range, but Range#include? performs
some conversions (like calling to_int) while Range#cover? does a
straight comparison.
By the way, the docs show this difference in the examples:
http://rdoc.info/stdlib/core/Range#cover%3F-instance_method
http://rdoc.info/stdlib/core/Range#include%3F-instance_method
-Justin
Thanks for your times!
Now my another question is :
ranges =[(1…10), (60…80), (200…400)]
numbers = [123, 700, 567]
numbers.any?{|x| ranges.any? {|y| y.cover? x}} #=> false
The time complexity of the above program is O(mn),can it be improved?
m=size of numbers and n = size of ranges.