I have a method that gets an array of arrays and detects if any sub array is occurs more than one time, regardless of its order:
def has_similar_content?(array)
array.each.with_index do |prop1, index1|
array.each.with_index do |prop2, index2|
next if index1 == index2
return true if prop1.sort == prop2.sort
end
end
false
end
> has_similar_content?([%w[white xl], %w[red xl]])
=> false
> has_similar_content?([%w[blue xl], %w[xl blue cotton]])
=> false
> has_similar_content?([%w[blue xl], %w[xl blue]])
=> true
> has_similar_content?([%w[xl green], %w[red xl], %w[green xl]])
=> true
My problem is the runtime of this method, it has a quadratic complexity and needs an additional sort of the arrays to detect if the elements are the same.
Is there a more efficient way to do this?
Array#|(intersection) method? Or is intersect not an option because this is some kind of homework?arrof arrays, I wish to determine if there exists at least one distinct pair of elements ofarr,aandb, such that every element ofais contained inband every element ofbis contained ina." You need something like that at the beginning of your question. "Similar" is a useless term.