32042

Question:

I want to find out if an array is an ordered subset of another array:

<ul><li>`[1,2]`

is an ordered subset of `[1,2,3]`

</li>
<li>`[1,3]`

is an ordered subset of `[1,2,3]`

</li>
<li>`[2,1]`

is not an ordered subset of `[1,2,3]`

</li>
</ul>I've found some solutions to this, but every solution ignores the order. Every method I've seen so far ignores the order of the arrays:

```
[1,2,3] - [2,1] #=> [3]
[1,2,3] & [2,1] #=> [1,2]
[1,2,3].to_set.superset?([2,1].to_set) #=> true
```

<strong>Update:</strong> Based on the discussion below, I've updated my question.

Answer1:##
```
b == a & b
```

That checks whether `b`

is contained in `a`

in the same order.

In other words: In general you have B⊆A ⇔ B=A∩B. And Ruby's `Array#&`

preserves the order (of the left operand).

##
```
a = [1,2,3]
b = [2,1]
p a.each_cons(b.size).any?{|slice| slice == b} # => false
```

Answer3:Given two arrays, `arr`

and `sub`

, this is a way to determine if there exists an array of strictly increasing indices, `indices`

, such that `arr.values_at(*indices) == sub`

.

```
def ordered?(arr, sub)
sub.each do |c|
i = arr.index(c)
return false if i.nil?
arr = arr[i+1..-1]
end
true
end
ordered?([1,2,3], [1,2]) #=> true
ordered?([1,2,3], [2,3]) #=> true
ordered?([1,2,3], [1,3]) #=> true
ordered?([1,2,3], [3,1]) #=> false
ordered?([1,2,5,2,4,3,4], [2,2,3]) #=> true
```

Note that @StefanPochmann suggested a more compact way of writing this in a comment below.