Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if array is an ordered subset

Tags:

ruby

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.

like image 725
23tux Avatar asked Dec 04 '17 15:12

23tux


People also ask

How do you check if an array is subset of another array JS?

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.

How do you check if an array is a subarray?

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.

How do you check if an array is a subset of another in PHP?

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'].


3 Answers

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).

like image 156
Stefan Pochmann Avatar answered Sep 25 '22 15:09

Stefan Pochmann


a = [1,2,3]
b = [2,1]

p a.each_cons(b.size).any?{|slice| slice == b} # => false
like image 41
steenslag Avatar answered Sep 22 '22 15:09

steenslag


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.

like image 25
Cary Swoveland Avatar answered Sep 24 '22 15:09

Cary Swoveland