Testing for subarrays

M

Michel Demazure

I want to check whether a given array contains a given subarray and
return the corresponding range.
Is there a builtin method ? If not, do you have better than this :

class Array
def look_up(sub_array)
len = sub_array.size
self.each_cons(len).with_index do |cons, index|
return Range.new(index, index + len - 1) if cons == sub_array
end
nil
end
end

_md
 
J

Jesús Gabriel y Galán

I want to check whether a given array contains a given subarray and
return the corresponding range.
Is there a builtin method ? If not, do you have better than this :

class Array
=A0def look_up(sub_array)
=A0 =A0len =3D sub_array.size
=A0 =A0self.each_cons(len).with_index do |cons, index|
=A0 =A0 =A0return Range.new(index, index + len - 1) if cons =3D=3D sub_ar= ray
=A0 =A0end
=A0 =A0nil
=A0end
end

Not necessarily better:

irb(main):001:0> a =3D [1,2,3,4,5,6,7,8]
=3D> [1, 2, 3, 4, 5, 6, 7, 8]
irb(main):002:0> b =3D [4,5,6]
=3D> [4, 5, 6]
irb(main):004:0> a.each_cons(b.size).to_a.index(b)
=3D> 3
irb(main):005:0> a.each_cons(b.size).to_a.index([5,1,2])
=3D> nil

Jesus.
 
M

Michel Demazure

David said:
Here's another way that is more verbose but that doesn't create the
whole array (which probably doesn't matter anyway, unless it's a huge
array and you're cycle-shaving). I also prefer extending individual
objects, rather than adding to Array.

module SubArrayFinder
def look_up(sub_array)
sub_size = sub_array.size
index = find_index.with_index do |e,i|
self[i, sub_size] == sub_array
end
return(index..index+sub_size-1) if index
end
end

Comparing with my original proposal, a side question is whether using
each_cons is faster, or not, that iterating with self[i, sub_size]...

_md
 
M

Michel Demazure

Michel said:
Comparing with my original proposal, a side question is whether using
each_cons is faster, or not, that iterating with self[i, sub_size]...

_md

sub("that", "than"), sorry
_md
 

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

No members online now.

Forum statistics

Threads
474,141
Messages
2,570,817
Members
47,367
Latest member
mahdiharooniir

Latest Threads

Top