#Godot 4.6 Question about a better way of getting the biggest or the smallest of an int array

1 messages · Page 1 of 1 (latest)

mellow blade
#

ok so im making an ant simulator currently and i dont want to make a for loop for every ant so i want a better way on going through the overlapping bodies without going through a for loop to save performance, there will be about 5 to 20 bodies every time so is there a better way than going through every one of them

misty robinBOT
mellow blade
carmine blade
#

get your array of ants. Then map them into an array of distance SQUARED to your target point. Then use either min or max on that array.

#

and use that index to select the right ant.

#

Well, max and min wil give you the VALUE. You'll need extra work to get the index

#

Both finding the min/max and then finding the index of that value add up to be O(2n), which scales all right especially if you let the C++ do the work for you

#

Technically O(3n) if you count mapping the ants to distances squared.

#

Still workable

#

However, it's workable if only a few units are doing this loop every frame, or if they are staggered (one frame, group A gets to tick, next frame, Group B ticks) though that can be a bit cursed

Truthfully, what you've stumbled upon is a non-trivial problem.

#

If all ants have to tick at the once, and check every other ant, you run into O(n^2) which does not scale at all.

If all ants MUST tick every frame, then you have to get into spatial data structures

#

The simplest example being, you divide the world into squares, and use those squares as "buckets" to put the ants in, and an ant only checks ants that are 1 or 2 squares away instead of every ant on the map.

Basically it is a cheap low-pass filter that filters out ants that are absolutely not in range first.

mellow blade
#

Thanks I'll try that

#

Well I'll try these