Jeremy Rodi Jeremy Rodi - 23 days ago 9
Ruby Question

How can I check if another array is a subsequence of the other?

I have two arrays; one of them,

b
, is probably a subset of the other,
a
; how can I check if
b
is a subsequence of
a
?

Basically,
[3, 4, 5]
would be a subsequence of
(1..10).to_a
, but not
(1..10).to_a.shuffle
.

Answer

Maybe not the most elegant solution, but should work for sure. Simple brute force:

def substring?(a, b)
  position = 0
  a.each_with_index do |v, i|
    if v == b[position] and (i + b.size - position) <= a.size
      position += 1
    elsif position == b.size
      return true
    else
      position = 0
    end
  end

  position == b.size
end

where b is your array and a is a candidate subset.