I want to find out if an array is an ordered subset of another array:
[1,2]
is an ordered subset of [1,2,3]
[1,3]
is an ordered subset of [1,2,3]
[2,1]
is not an ordered subset of [1,2,3]
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
Update: Based on the discussion below, I've updated my question.
Naive Approach to Find whether an array is subset of another array. Use two loops: The outer loop picks all the elements of arr2[] one by one. The inner loop linearly searches for the element picked by the outer loop. If all elements are found then return 1, else return 0.
Simple Approach: A simple approach is to run two nested loops and generate all subarrays of the array A[] and use one more loop to check if any of the subarray of A[] is equal to the array B[]. Efficient Approach : An efficient approach is to use two pointers to traverse both the array simultaneously.
Simple: use array subtraction. On array subtraction, you will know whether or not one array is a subset of the other. You can use array_intersect also. array_diff(['a', 'b', 'c'], ['a', 'b']) will return ['c'].
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With