0 votes

I have two arrays, each containing a few thousand Vector2s.

I want to find out if they intersect, but don't care about the intersection itself.

Currently, I do it this way.

func intersects(array1, array2):
    var intersect = false
    for item in array1:
        if item in array2:
            intersect = true
    return intersect

I do not feel like this is the most optimal way to do it. In fact, I am experiencing performance issues doing it this way.

What is the fastest way to check arrays for intersection?

I am open to using a different data type, like dictionaries. I am even open to using a different type of object for my elements, for example, using subarrays rather than Vector2s.

in Engine by (1,516 points)

1 Answer

+1 vote

A way you could do it is like this:

func intersect(array1, array2):
  var intersection = false
  for item in array1:
    if array2.has(item):
      intersection = true
  return intersection

A little different from your code. The has() method may speed things up.

You could even get more sophisticated, and return the elements which do intersect:

func intersect(arra1, array2):
  var intersection = []
    for item in array1:
      if array2.has(item):
  return intersection

Hope this helps.

by (1,668 points)
edited by
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.