Getting N points nearst to the control point

I’m working on multiplayer realtime strategy game. Today I implemented method for getting 3 units of the player which are nearst to the station creation point. See below. As you can see it’s regular problem of getting N min(max) elements of array. The task looks pretty regular, even standard. But I can’t say that such tasks are daily ones. And what about you?

                // get 3 units nearst to the x, y
                var distances = new int[StationCreationUnitsNumber];
                var units = new Unit[StationCreationUnitsNumber];
                var taken = 0;
                foreach (var unit in player.Units)
                    var d = _distance2(unit.X, unit.Y, x, y);

                    // check new point against taken ones
                    for (var i = 0; i < taken; ++i)
                        // if new point should be taken
                        if (d <= distances[i])
                            // shift already taken points
                            for (var j = taken – 1; j > i; –j)
                                distances[j] = distances[j – 1];
                                units[j] = units[j – 1];

                            // take the point and jump to process next one
                            distances[i] = d;
                            units[i] = unit;
                            goto units_loop_end;

                    // take initial point anyway
                    if (taken < StationCreationUnitsNumber)
                        distances[taken] = d;
                        units[taken] = unit;



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: