Algorithm - O (1) to check if a muscle is hanging from one of an array of circles

usually to check that the mouse move

event is x

and y

intercepts any polygon within the polygon array:

on mousemove (e)->
  for c in circles
     if intercept(e.x, e.y, c)
        ...

      

just wondering if I can test it without a loop for

, like:

on mousemove (e)->
  i = calidx(e.x, e.y)
  if intercept(e.x, e.y, circles[i])

      

It seems that every event loop mousemove

through all array elements is inefficient

Can O (1) complexity be used to find out which element of an array is hovering?

+3


source to share


1 answer


Using a lookup table makes it amortized O (1) (but painful to tweak / update)

One way to do this with amortized O (1) is to use a table lookup. This means that you need to store each pixel coordinate with the ID of the circle it belongs to:

pixel (0,0) โ†’ no circle

pixel (0,1) -> circle # 1

pixel (0,2) โ†’ circle # 1, circle # 2

...

So, you can quickly find a table with a specific pixel coordinate and get the circles it belongs to. This search can be done with amortized O (1).

However, it is a pain in the ass to set the table up or update it



The algorithm for setting up the lookup table is painful, very complex. You will need to fill in all the pixel coordinates of each of your circles and create a complete table. It is very difficult and updating the new position of the existing circles is even worse. Some computation is required to update the lookup table.

The approach is possible if:

  • Your circles are static. Once the circles have been configured, they will not move or change.
  • You have a small canvas.

On the contrary, it is evil and worse when:

  • Your circles are dynamic. They keep moving, resizing, adding or removing all the time. This causes the update phase to be severe overhead.
  • You have a large canvas.
+2


source







All Articles