0

最初に背景を少し。ロケーション間の「ルート」を生成するシステムを開発しています。場所には、それに隣接するものに限定されない、事前定義された近隣のリストがあります。検索では、ターゲットの目的地に (数値的に) 最も近い近隣を選択することで、目的地に向かって最適な移動を行っていると安全に想定できます。

以下に示すような作業コードがあります。

public Route GetRoute(int StartPoint, int Destination)
{
    Route returnRoute = new Route();
    returnRoute.steps = new List<int>();
    bool locationReached = false;
    int selectedNeighbour;
    int distanceFromTarget;
    int currentPoint = StartPoint; // set the current point to the start point

    while (!locationReached)
    {
        selectedNeighbour = 0;
        distanceFromTarget = 5000; // nominal amount guaranteed to be overwritten

        var neighbours = locations.FirstOrDefault(l => l.LocationID == currentPoint).Neighbours;

        for (int i = 0; i < neighbours.Length; i++)
        {
            // get the current neighbours, then check proximity
            int currentNeighbour = neighbours[i];
            int tempDistance = Math.Abs( currentNeighbour - Destination );

            // if nearer than previous neighbour, set it as the chosen location
            if ( tempDistance < distanceFromTarget )
            {
                distanceFromTarget = tempDistance;
                selectedNeighbour = currentNeighbour;

                // if the selected neighbour is the destination, we're done
                if ( selectedNeighbour == Destination )
                    locationReached = true;
            }

        } // for

        // add the selected neighbour if we found one
        if ( selectedNeighbour != 0 )
        {
            currentPoint = selectedNeighbour;
            returnRoute.steps.Add(selectedNeighbour);
        }
        else 
        {
            Debug.Log ("No Route Found");
            return returnRoute; 
        }

    } // while

    return returnRoute;
}

私の質問は、隣人 (int[]) 変数のループに関するものです。これを最適化するにはどうすればよいでしょうか。linq と順序付けの使用を見てきましたが、このアプローチは非効率的かもしれないというコメントもありました。ここでは、整頓よりも効率が必要です。

どうもありがとう。

4

0 に答える 0