Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Array contained in Array, any order [duplicate]

Suppose I have the following Ruby code:

array_1 = ['a', 'b']
array_2 = ['a', 'b', 'c']

some_function(array_1, array_2) # => True
some_function(array_2, array_1) # => False
some_function(['a', 'b'], ['a', 'd']) # => False
some_function(['x', 'y'], array_2) # => False

I am pretty much looking for some_function to return True when Parameter 2 contains all of the elements in Parameter 1.

like image 535
Mike Avatar asked Oct 09 '10 19:10

Mike


People also ask

How do you check if there are duplicates in an array Ruby?

select { array. count } is a nested loop, you're doing an O(n^2) complex algorithm for something which can be done in O(n). You're right, to solve this Skizit's question we can use in O(n); but in order to find out which elements are duplicated an O(n^2) algo is the only way I can think of so far.

What does .select do in Ruby?

Ruby | Array select() function Array#select() : select() is a Array class method which returns a new array containing all elements of array for which the given block returns a true value. Return: A new array containing all elements of array for which the given block returns a true value.

How do you sort an array of arrays in Ruby?

You can use the sort method on an array, hash, or another Enumerable object & you'll get the default sorting behavior (sort based on <=> operator) You can use sort with a block, and two block arguments, to define how one object is different than another (block should return 1, 0, or -1)


2 Answers

def f a,b
    (a-b).empty?
end
like image 132
Nakilon Avatar answered Oct 29 '22 03:10

Nakilon


From a previous post,

def f a,b
    (a-b).empty?
end

will not work the way you expect, for example:

a1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
a2 = [2, 3, 5, 9]

(a1-a2).empty? # returns true

however,

a1-a2 # returns [1, 4, 6, 7, 8], not empty

thus f returns false.

A more accurate solution, if you want a one-liner would be:

def f a,b
    a&b == b
end

a&b will return all elements that are in both a and b then we check to see if that is equal to b

For ambiguity sake:

def f a,b
    (a&b == a) || (a&b == b)
end
like image 26
Iggloo Dev Avatar answered Oct 29 '22 04:10

Iggloo Dev